babylon.max.js 3.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604
  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. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Scalar = (function () {
  67. function Scalar() {
  68. }
  69. /**
  70. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  71. */
  72. Scalar.Lerp = function (start, end, amount) {
  73. return start + ((end - start) * amount);
  74. };
  75. /**
  76. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  77. */
  78. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  79. var squared = amount * amount;
  80. var cubed = amount * squared;
  81. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  82. var part2 = (-2.0 * cubed) + (3.0 * squared);
  83. var part3 = (cubed - (2.0 * squared)) + amount;
  84. var part4 = cubed - squared;
  85. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  86. };
  87. return Scalar;
  88. }());
  89. BABYLON.Scalar = Scalar;
  90. var Color3 = (function () {
  91. /**
  92. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  93. */
  94. function Color3(r, g, b) {
  95. if (r === void 0) { r = 0; }
  96. if (g === void 0) { g = 0; }
  97. if (b === void 0) { b = 0; }
  98. this.r = r;
  99. this.g = g;
  100. this.b = b;
  101. }
  102. /**
  103. * Returns a string with the Color3 current values.
  104. */
  105. Color3.prototype.toString = function () {
  106. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  107. };
  108. /**
  109. * Returns the string "Color3".
  110. */
  111. Color3.prototype.getClassName = function () {
  112. return "Color3";
  113. };
  114. /**
  115. * Returns the Color3 hash code.
  116. */
  117. Color3.prototype.getHashCode = function () {
  118. var hash = this.r || 0;
  119. hash = (hash * 397) ^ (this.g || 0);
  120. hash = (hash * 397) ^ (this.b || 0);
  121. return hash;
  122. };
  123. // Operators
  124. /**
  125. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  126. * Returns the Color3.
  127. */
  128. Color3.prototype.toArray = function (array, index) {
  129. if (index === undefined) {
  130. index = 0;
  131. }
  132. array[index] = this.r;
  133. array[index + 1] = this.g;
  134. array[index + 2] = this.b;
  135. return this;
  136. };
  137. /**
  138. * Returns a new Color4 object from the current Color3 and the passed alpha.
  139. */
  140. Color3.prototype.toColor4 = function (alpha) {
  141. if (alpha === void 0) { alpha = 1; }
  142. return new Color4(this.r, this.g, this.b, alpha);
  143. };
  144. /**
  145. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  146. */
  147. Color3.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. /**
  153. * Returns the luminance value (float).
  154. */
  155. Color3.prototype.toLuminance = function () {
  156. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  157. };
  158. /**
  159. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  160. * Returns this new object.
  161. */
  162. Color3.prototype.multiply = function (otherColor) {
  163. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  164. };
  165. /**
  166. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  167. * Returns the current Color3.
  168. */
  169. Color3.prototype.multiplyToRef = function (otherColor, result) {
  170. result.r = this.r * otherColor.r;
  171. result.g = this.g * otherColor.g;
  172. result.b = this.b * otherColor.b;
  173. return this;
  174. };
  175. /**
  176. * Boolean : True if the rgb values are equal to the passed ones.
  177. */
  178. Color3.prototype.equals = function (otherColor) {
  179. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  180. };
  181. /**
  182. * Boolean : True if the rgb values are equal to the passed ones.
  183. */
  184. Color3.prototype.equalsFloats = function (r, g, b) {
  185. return this.r === r && this.g === g && this.b === b;
  186. };
  187. /**
  188. * Multiplies in place each rgb value by scale.
  189. * Returns the updated Color3.
  190. */
  191. Color3.prototype.scale = function (scale) {
  192. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  193. };
  194. /**
  195. * Multiplies the rgb values by scale and stores the result into "result".
  196. * Returns the unmodified current Color3.
  197. */
  198. Color3.prototype.scaleToRef = function (scale, result) {
  199. result.r = this.r * scale;
  200. result.g = this.g * scale;
  201. result.b = this.b * scale;
  202. return this;
  203. };
  204. /**
  205. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  206. */
  207. Color3.prototype.add = function (otherColor) {
  208. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  209. };
  210. /**
  211. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  212. * Returns the unmodified current Color3.
  213. */
  214. Color3.prototype.addToRef = function (otherColor, result) {
  215. result.r = this.r + otherColor.r;
  216. result.g = this.g + otherColor.g;
  217. result.b = this.b + otherColor.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  222. */
  223. Color3.prototype.subtract = function (otherColor) {
  224. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  225. };
  226. /**
  227. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  228. * Returns the unmodified current Color3.
  229. */
  230. Color3.prototype.subtractToRef = function (otherColor, result) {
  231. result.r = this.r - otherColor.r;
  232. result.g = this.g - otherColor.g;
  233. result.b = this.b - otherColor.b;
  234. return this;
  235. };
  236. /**
  237. * Returns a new Color3 copied the current one.
  238. */
  239. Color3.prototype.clone = function () {
  240. return new Color3(this.r, this.g, this.b);
  241. };
  242. /**
  243. * Copies the rgb values from the source in the current Color3.
  244. * Returns the updated Color3.
  245. */
  246. Color3.prototype.copyFrom = function (source) {
  247. this.r = source.r;
  248. this.g = source.g;
  249. this.b = source.b;
  250. return this;
  251. };
  252. /**
  253. * Updates the Color3 rgb values from the passed floats.
  254. * Returns the Color3.
  255. */
  256. Color3.prototype.copyFromFloats = function (r, g, b) {
  257. this.r = r;
  258. this.g = g;
  259. this.b = b;
  260. return this;
  261. };
  262. /**
  263. * Updates the Color3 rgb values from the passed floats.
  264. * Returns the Color3.
  265. */
  266. Color3.prototype.set = function (r, g, b) {
  267. return this.copyFromFloats(r, g, b);
  268. };
  269. /**
  270. * Returns the Color3 hexadecimal code as a string.
  271. */
  272. Color3.prototype.toHexString = function () {
  273. var intR = (this.r * 255) | 0;
  274. var intG = (this.g * 255) | 0;
  275. var intB = (this.b * 255) | 0;
  276. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  277. };
  278. /**
  279. * Returns a new Color3 converted to linear space.
  280. */
  281. Color3.prototype.toLinearSpace = function () {
  282. var convertedColor = new Color3();
  283. this.toLinearSpaceToRef(convertedColor);
  284. return convertedColor;
  285. };
  286. /**
  287. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  288. * Returns the unmodified Color3.
  289. */
  290. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  291. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  292. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  293. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  294. return this;
  295. };
  296. /**
  297. * Returns a new Color3 converted to gamma space.
  298. */
  299. Color3.prototype.toGammaSpace = function () {
  300. var convertedColor = new Color3();
  301. this.toGammaSpaceToRef(convertedColor);
  302. return convertedColor;
  303. };
  304. /**
  305. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  306. * Returns the unmodified Color3.
  307. */
  308. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  309. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  310. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  311. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  312. return this;
  313. };
  314. // Statics
  315. /**
  316. * Creates a new Color3 from the string containing valid hexadecimal values.
  317. */
  318. Color3.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  320. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  321. return new Color3(0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. return Color3.FromInts(r, g, b);
  327. };
  328. /**
  329. * Creates a new Vector3 from the startind index of the passed array.
  330. */
  331. Color3.FromArray = function (array, offset) {
  332. if (offset === void 0) { offset = 0; }
  333. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  334. };
  335. /**
  336. * Creates a new Color3 from integer values ( < 256).
  337. */
  338. Color3.FromInts = function (r, g, b) {
  339. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  340. };
  341. /**
  342. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  343. */
  344. Color3.Lerp = function (start, end, amount) {
  345. var r = start.r + ((end.r - start.r) * amount);
  346. var g = start.g + ((end.g - start.g) * amount);
  347. var b = start.b + ((end.b - start.b) * amount);
  348. return new Color3(r, g, b);
  349. };
  350. Color3.Red = function () { return new Color3(1, 0, 0); };
  351. Color3.Green = function () { return new Color3(0, 1, 0); };
  352. Color3.Blue = function () { return new Color3(0, 0, 1); };
  353. Color3.Black = function () { return new Color3(0, 0, 0); };
  354. Color3.White = function () { return new Color3(1, 1, 1); };
  355. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  356. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  357. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  358. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  359. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  360. return Color3;
  361. }());
  362. BABYLON.Color3 = Color3;
  363. var Color4 = (function () {
  364. /**
  365. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  366. */
  367. function Color4(r, g, b, a) {
  368. this.r = r;
  369. this.g = g;
  370. this.b = b;
  371. this.a = a;
  372. }
  373. // Operators
  374. /**
  375. * Adds in place the passed Color4 values to the current Color4.
  376. * Returns the updated Color4.
  377. */
  378. Color4.prototype.addInPlace = function (right) {
  379. this.r += right.r;
  380. this.g += right.g;
  381. this.b += right.b;
  382. this.a += right.a;
  383. return this;
  384. };
  385. /**
  386. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  387. */
  388. Color4.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. /**
  394. * Stores from the starting index in the passed array the Color4 successive values.
  395. * Returns the Color4.
  396. */
  397. Color4.prototype.toArray = function (array, index) {
  398. if (index === undefined) {
  399. index = 0;
  400. }
  401. array[index] = this.r;
  402. array[index + 1] = this.g;
  403. array[index + 2] = this.b;
  404. array[index + 3] = this.a;
  405. return this;
  406. };
  407. /**
  408. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  409. */
  410. Color4.prototype.add = function (right) {
  411. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  412. };
  413. /**
  414. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  415. */
  416. Color4.prototype.subtract = function (right) {
  417. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  418. };
  419. /**
  420. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  421. * Returns the Color4.
  422. */
  423. Color4.prototype.subtractToRef = function (right, result) {
  424. result.r = this.r - right.r;
  425. result.g = this.g - right.g;
  426. result.b = this.b - right.b;
  427. result.a = this.a - right.a;
  428. return this;
  429. };
  430. /**
  431. * Creates a new Color4 with the current Color4 values multiplied by scale.
  432. */
  433. Color4.prototype.scale = function (scale) {
  434. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  435. };
  436. /**
  437. * Multiplies the current Color4 values by scale and stores the result in "result".
  438. * Returns the Color4.
  439. */
  440. Color4.prototype.scaleToRef = function (scale, result) {
  441. result.r = this.r * scale;
  442. result.g = this.g * scale;
  443. result.b = this.b * scale;
  444. result.a = this.a * scale;
  445. return this;
  446. };
  447. /**
  448. * Multipy an RGBA Color4 value by another and return a new Color4 object
  449. * @param color The Color4 (RGBA) value to multiply by
  450. * @returns A new Color4.
  451. */
  452. Color4.prototype.multiply = function (color) {
  453. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  454. };
  455. /**
  456. * Multipy an RGBA Color4 value by another and push the result in a reference value
  457. * @param color The Color4 (RGBA) value to multiply by
  458. * @param result The Color4 (RGBA) to fill the result in
  459. * @returns the result Color4.
  460. */
  461. Color4.prototype.multiplyToRef = function (color, result) {
  462. result.r = this.r * color.r;
  463. result.g = this.g * color.g;
  464. result.b = this.b * color.b;
  465. result.a = this.a * color.a;
  466. return result;
  467. };
  468. /**
  469. * Returns a string with the Color4 values.
  470. */
  471. Color4.prototype.toString = function () {
  472. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  473. };
  474. /**
  475. * Returns the string "Color4"
  476. */
  477. Color4.prototype.getClassName = function () {
  478. return "Color4";
  479. };
  480. /**
  481. * Return the Color4 hash code as a number.
  482. */
  483. Color4.prototype.getHashCode = function () {
  484. var hash = this.r || 0;
  485. hash = (hash * 397) ^ (this.g || 0);
  486. hash = (hash * 397) ^ (this.b || 0);
  487. hash = (hash * 397) ^ (this.a || 0);
  488. return hash;
  489. };
  490. /**
  491. * Creates a new Color4 copied from the current one.
  492. */
  493. Color4.prototype.clone = function () {
  494. return new Color4(this.r, this.g, this.b, this.a);
  495. };
  496. /**
  497. * Copies the passed Color4 values into the current one.
  498. * Returns the updated Color4.
  499. */
  500. Color4.prototype.copyFrom = function (source) {
  501. this.r = source.r;
  502. this.g = source.g;
  503. this.b = source.b;
  504. this.a = source.a;
  505. return this;
  506. };
  507. /**
  508. * Copies the passed float values into the current one.
  509. * Returns the updated Color4.
  510. */
  511. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  512. this.r = r;
  513. this.g = g;
  514. this.b = b;
  515. this.a = a;
  516. return this;
  517. };
  518. /**
  519. * Copies the passed float values into the current one.
  520. * Returns the updated Color4.
  521. */
  522. Color4.prototype.set = function (r, g, b, a) {
  523. return this.copyFromFloats(r, g, b, a);
  524. };
  525. /**
  526. * Returns a string containing the hexadecimal Color4 code.
  527. */
  528. Color4.prototype.toHexString = function () {
  529. var intR = (this.r * 255) | 0;
  530. var intG = (this.g * 255) | 0;
  531. var intB = (this.b * 255) | 0;
  532. var intA = (this.a * 255) | 0;
  533. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  534. };
  535. // Statics
  536. /**
  537. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  538. */
  539. Color4.FromHexString = function (hex) {
  540. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  541. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  542. return new Color4(0.0, 0.0, 0.0, 0.0);
  543. }
  544. var r = parseInt(hex.substring(1, 3), 16);
  545. var g = parseInt(hex.substring(3, 5), 16);
  546. var b = parseInt(hex.substring(5, 7), 16);
  547. var a = parseInt(hex.substring(7, 9), 16);
  548. return Color4.FromInts(r, g, b, a);
  549. };
  550. /**
  551. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  552. */
  553. Color4.Lerp = function (left, right, amount) {
  554. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  555. Color4.LerpToRef(left, right, amount, result);
  556. return result;
  557. };
  558. /**
  559. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  560. */
  561. Color4.LerpToRef = function (left, right, amount, result) {
  562. result.r = left.r + (right.r - left.r) * amount;
  563. result.g = left.g + (right.g - left.g) * amount;
  564. result.b = left.b + (right.b - left.b) * amount;
  565. result.a = left.a + (right.a - left.a) * amount;
  566. };
  567. /**
  568. * Creates a new Color4 from the starting index element of the passed array.
  569. */
  570. Color4.FromArray = function (array, offset) {
  571. if (offset === void 0) { offset = 0; }
  572. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  573. };
  574. /**
  575. * Creates a new Color4 from the passed integers ( < 256 ).
  576. */
  577. Color4.FromInts = function (r, g, b, a) {
  578. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  579. };
  580. Color4.CheckColors4 = function (colors, count) {
  581. // Check if color3 was used
  582. if (colors.length === count * 3) {
  583. var colors4 = [];
  584. for (var index = 0; index < colors.length; index += 3) {
  585. var newIndex = (index / 3) * 4;
  586. colors4[newIndex] = colors[index];
  587. colors4[newIndex + 1] = colors[index + 1];
  588. colors4[newIndex + 2] = colors[index + 2];
  589. colors4[newIndex + 3] = 1.0;
  590. }
  591. return colors4;
  592. }
  593. return colors;
  594. };
  595. return Color4;
  596. }());
  597. BABYLON.Color4 = Color4;
  598. var Vector2 = (function () {
  599. /**
  600. * Creates a new Vector2 from the passed x and y coordinates.
  601. */
  602. function Vector2(x, y) {
  603. this.x = x;
  604. this.y = y;
  605. }
  606. /**
  607. * Returns a string with the Vector2 coordinates.
  608. */
  609. Vector2.prototype.toString = function () {
  610. return "{X: " + this.x + " Y:" + this.y + "}";
  611. };
  612. /**
  613. * Returns the string "Vector2"
  614. */
  615. Vector2.prototype.getClassName = function () {
  616. return "Vector2";
  617. };
  618. /**
  619. * Returns the Vector2 hash code as a number.
  620. */
  621. Vector2.prototype.getHashCode = function () {
  622. var hash = this.x || 0;
  623. hash = (hash * 397) ^ (this.y || 0);
  624. return hash;
  625. };
  626. // Operators
  627. /**
  628. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  629. * Returns the Vector2.
  630. */
  631. Vector2.prototype.toArray = function (array, index) {
  632. if (index === void 0) { index = 0; }
  633. array[index] = this.x;
  634. array[index + 1] = this.y;
  635. return this;
  636. };
  637. /**
  638. * Returns a new array with 2 elements : the Vector2 coordinates.
  639. */
  640. Vector2.prototype.asArray = function () {
  641. var result = [];
  642. this.toArray(result, 0);
  643. return result;
  644. };
  645. /**
  646. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  647. * Returns the updated Vector2.
  648. */
  649. Vector2.prototype.copyFrom = function (source) {
  650. this.x = source.x;
  651. this.y = source.y;
  652. return this;
  653. };
  654. /**
  655. * Sets the Vector2 coordinates with the passed floats.
  656. * Returns the updated Vector2.
  657. */
  658. Vector2.prototype.copyFromFloats = function (x, y) {
  659. this.x = x;
  660. this.y = y;
  661. return this;
  662. };
  663. /**
  664. * Sets the Vector2 coordinates with the passed floats.
  665. * Returns the updated Vector2.
  666. */
  667. Vector2.prototype.set = function (x, y) {
  668. return this.copyFromFloats(x, y);
  669. };
  670. /**
  671. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  672. */
  673. Vector2.prototype.add = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  678. * Returns the Vector2.
  679. */
  680. Vector2.prototype.addToRef = function (otherVector, result) {
  681. result.x = this.x + otherVector.x;
  682. result.y = this.y + otherVector.y;
  683. return this;
  684. };
  685. /**
  686. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  687. * Returns the updated Vector2.
  688. */
  689. Vector2.prototype.addInPlace = function (otherVector) {
  690. this.x += otherVector.x;
  691. this.y += otherVector.y;
  692. return this;
  693. };
  694. /**
  695. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  696. */
  697. Vector2.prototype.addVector3 = function (otherVector) {
  698. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  699. };
  700. /**
  701. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  702. */
  703. Vector2.prototype.subtract = function (otherVector) {
  704. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  705. };
  706. /**
  707. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  708. * Returns the Vector2.
  709. */
  710. Vector2.prototype.subtractToRef = function (otherVector, result) {
  711. result.x = this.x - otherVector.x;
  712. result.y = this.y - otherVector.y;
  713. return this;
  714. };
  715. /**
  716. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.subtractInPlace = function (otherVector) {
  720. this.x -= otherVector.x;
  721. this.y -= otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Multiplies in place the current Vector2 coordinates by the passed ones.
  726. * Returns the updated Vector2.
  727. */
  728. Vector2.prototype.multiplyInPlace = function (otherVector) {
  729. this.x *= otherVector.x;
  730. this.y *= otherVector.y;
  731. return this;
  732. };
  733. /**
  734. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  735. */
  736. Vector2.prototype.multiply = function (otherVector) {
  737. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  738. };
  739. /**
  740. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  741. * Returns the Vector2.
  742. */
  743. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  744. result.x = this.x * otherVector.x;
  745. result.y = this.y * otherVector.y;
  746. return this;
  747. };
  748. /**
  749. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  750. */
  751. Vector2.prototype.multiplyByFloats = function (x, y) {
  752. return new Vector2(this.x * x, this.y * y);
  753. };
  754. /**
  755. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  756. */
  757. Vector2.prototype.divide = function (otherVector) {
  758. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  759. };
  760. /**
  761. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  762. * Returns the Vector2.
  763. */
  764. Vector2.prototype.divideToRef = function (otherVector, result) {
  765. result.x = this.x / otherVector.x;
  766. result.y = this.y / otherVector.y;
  767. return this;
  768. };
  769. /**
  770. * Returns a new Vector2 with current Vector2 negated coordinates.
  771. */
  772. Vector2.prototype.negate = function () {
  773. return new Vector2(-this.x, -this.y);
  774. };
  775. /**
  776. * Multiply the Vector2 coordinates by scale.
  777. * Returns the updated Vector2.
  778. */
  779. Vector2.prototype.scaleInPlace = function (scale) {
  780. this.x *= scale;
  781. this.y *= scale;
  782. return this;
  783. };
  784. /**
  785. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  786. */
  787. Vector2.prototype.scale = function (scale) {
  788. return new Vector2(this.x * scale, this.y * scale);
  789. };
  790. /**
  791. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  792. */
  793. Vector2.prototype.equals = function (otherVector) {
  794. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  795. };
  796. /**
  797. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  798. */
  799. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  800. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  801. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  802. };
  803. // Properties
  804. /**
  805. * Returns the vector length (float).
  806. */
  807. Vector2.prototype.length = function () {
  808. return Math.sqrt(this.x * this.x + this.y * this.y);
  809. };
  810. /**
  811. * Returns the vector squared length (float);
  812. */
  813. Vector2.prototype.lengthSquared = function () {
  814. return (this.x * this.x + this.y * this.y);
  815. };
  816. // Methods
  817. /**
  818. * Normalize the vector.
  819. * Returns the updated Vector2.
  820. */
  821. Vector2.prototype.normalize = function () {
  822. var len = this.length();
  823. if (len === 0)
  824. return this;
  825. var num = 1.0 / len;
  826. this.x *= num;
  827. this.y *= num;
  828. return this;
  829. };
  830. /**
  831. * Returns a new Vector2 copied from the Vector2.
  832. */
  833. Vector2.prototype.clone = function () {
  834. return new Vector2(this.x, this.y);
  835. };
  836. // Statics
  837. /**
  838. * Returns a new Vector2(0, 0)
  839. */
  840. Vector2.Zero = function () {
  841. return new Vector2(0, 0);
  842. };
  843. /**
  844. * Returns a new Vector2 set from the passed index element of the passed array.
  845. */
  846. Vector2.FromArray = function (array, offset) {
  847. if (offset === void 0) { offset = 0; }
  848. return new Vector2(array[offset], array[offset + 1]);
  849. };
  850. /**
  851. * Sets "result" from the passed index element of the passed array.
  852. */
  853. Vector2.FromArrayToRef = function (array, offset, result) {
  854. result.x = array[offset];
  855. result.y = array[offset + 1];
  856. };
  857. /**
  858. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  859. */
  860. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  861. var squared = amount * amount;
  862. var cubed = amount * squared;
  863. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  864. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  865. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  866. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  867. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  868. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  869. return new Vector2(x, y);
  870. };
  871. /**
  872. * 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".
  873. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  874. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  875. */
  876. Vector2.Clamp = function (value, min, max) {
  877. var x = value.x;
  878. x = (x > max.x) ? max.x : x;
  879. x = (x < min.x) ? min.x : x;
  880. var y = value.y;
  881. y = (y > max.y) ? max.y : y;
  882. y = (y < min.y) ? min.y : y;
  883. return new Vector2(x, y);
  884. };
  885. /**
  886. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  887. */
  888. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  889. var squared = amount * amount;
  890. var cubed = amount * squared;
  891. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  892. var part2 = (-2.0 * cubed) + (3.0 * squared);
  893. var part3 = (cubed - (2.0 * squared)) + amount;
  894. var part4 = cubed - squared;
  895. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  896. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  897. return new Vector2(x, y);
  898. };
  899. /**
  900. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  901. */
  902. Vector2.Lerp = function (start, end, amount) {
  903. var x = start.x + ((end.x - start.x) * amount);
  904. var y = start.y + ((end.y - start.y) * amount);
  905. return new Vector2(x, y);
  906. };
  907. /**
  908. * Returns the dot product (float) of the vector "left" and the vector "right".
  909. */
  910. Vector2.Dot = function (left, right) {
  911. return left.x * right.x + left.y * right.y;
  912. };
  913. /**
  914. * Returns a new Vector2 equal to the normalized passed vector.
  915. */
  916. Vector2.Normalize = function (vector) {
  917. var newVector = vector.clone();
  918. newVector.normalize();
  919. return newVector;
  920. };
  921. /**
  922. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  923. */
  924. Vector2.Minimize = function (left, right) {
  925. var x = (left.x < right.x) ? left.x : right.x;
  926. var y = (left.y < right.y) ? left.y : right.y;
  927. return new Vector2(x, y);
  928. };
  929. /**
  930. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  931. */
  932. Vector2.Maximize = function (left, right) {
  933. var x = (left.x > right.x) ? left.x : right.x;
  934. var y = (left.y > right.y) ? left.y : right.y;
  935. return new Vector2(x, y);
  936. };
  937. /**
  938. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  939. */
  940. Vector2.Transform = function (vector, transformation) {
  941. var r = Vector2.Zero();
  942. Vector2.TransformToRef(vector, transformation, r);
  943. return r;
  944. };
  945. /**
  946. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  947. */
  948. Vector2.TransformToRef = function (vector, transformation, result) {
  949. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  950. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  951. result.x = x;
  952. result.y = y;
  953. };
  954. /**
  955. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  956. */
  957. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  958. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  959. var sign = a < 0 ? -1 : 1;
  960. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  961. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  962. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  963. };
  964. /**
  965. * Returns the distance (float) between the vectors "value1" and "value2".
  966. */
  967. Vector2.Distance = function (value1, value2) {
  968. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  969. };
  970. /**
  971. * Returns the squared distance (float) between the vectors "value1" and "value2".
  972. */
  973. Vector2.DistanceSquared = function (value1, value2) {
  974. var x = value1.x - value2.x;
  975. var y = value1.y - value2.y;
  976. return (x * x) + (y * y);
  977. };
  978. /**
  979. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  980. */
  981. Vector2.Center = function (value1, value2) {
  982. var center = value1.add(value2);
  983. center.scaleInPlace(0.5);
  984. return center;
  985. };
  986. /**
  987. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  988. */
  989. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  990. var l2 = Vector2.DistanceSquared(segA, segB);
  991. if (l2 === 0.0) {
  992. return Vector2.Distance(p, segA);
  993. }
  994. var v = segB.subtract(segA);
  995. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  996. var proj = segA.add(v.multiplyByFloats(t, t));
  997. return Vector2.Distance(p, proj);
  998. };
  999. return Vector2;
  1000. }());
  1001. BABYLON.Vector2 = Vector2;
  1002. var Vector3 = (function () {
  1003. /**
  1004. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1005. * A Vector3 is the main object used in 3D geometry.
  1006. * It can represent etiher the coordinates of a point the space, either a direction.
  1007. */
  1008. function Vector3(x, y, z) {
  1009. this.x = x;
  1010. this.y = y;
  1011. this.z = z;
  1012. }
  1013. /**
  1014. * Returns a string with the Vector3 coordinates.
  1015. */
  1016. Vector3.prototype.toString = function () {
  1017. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1018. };
  1019. /**
  1020. * Returns the string "Vector3"
  1021. */
  1022. Vector3.prototype.getClassName = function () {
  1023. return "Vector3";
  1024. };
  1025. /**
  1026. * Returns the Vector hash code.
  1027. */
  1028. Vector3.prototype.getHashCode = function () {
  1029. var hash = this.x || 0;
  1030. hash = (hash * 397) ^ (this.y || 0);
  1031. hash = (hash * 397) ^ (this.z || 0);
  1032. return hash;
  1033. };
  1034. // Operators
  1035. /**
  1036. * Returns a new array with three elements : the coordinates the Vector3.
  1037. */
  1038. Vector3.prototype.asArray = function () {
  1039. var result = [];
  1040. this.toArray(result, 0);
  1041. return result;
  1042. };
  1043. /**
  1044. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1045. * Returns the Vector3.
  1046. */
  1047. Vector3.prototype.toArray = function (array, index) {
  1048. if (index === void 0) { index = 0; }
  1049. array[index] = this.x;
  1050. array[index + 1] = this.y;
  1051. array[index + 2] = this.z;
  1052. return this;
  1053. };
  1054. /**
  1055. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1056. */
  1057. Vector3.prototype.toQuaternion = function () {
  1058. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1059. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1060. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1061. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1062. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1063. var cosy = Math.cos(this.y * 0.5);
  1064. var siny = Math.sin(this.y * 0.5);
  1065. result.x = coszMinusx * siny;
  1066. result.y = -sinzMinusx * siny;
  1067. result.z = sinxPlusz * cosy;
  1068. result.w = cosxPlusz * cosy;
  1069. return result;
  1070. };
  1071. /**
  1072. * Adds the passed vector to the current Vector3.
  1073. * Returns the updated Vector3.
  1074. */
  1075. Vector3.prototype.addInPlace = function (otherVector) {
  1076. this.x += otherVector.x;
  1077. this.y += otherVector.y;
  1078. this.z += otherVector.z;
  1079. return this;
  1080. };
  1081. /**
  1082. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1083. */
  1084. Vector3.prototype.add = function (otherVector) {
  1085. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1086. };
  1087. /**
  1088. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1089. * Returns the current Vector3.
  1090. */
  1091. Vector3.prototype.addToRef = function (otherVector, result) {
  1092. result.x = this.x + otherVector.x;
  1093. result.y = this.y + otherVector.y;
  1094. result.z = this.z + otherVector.z;
  1095. return this;
  1096. };
  1097. /**
  1098. * Subtract the passed vector from the current Vector3.
  1099. * Returns the updated Vector3.
  1100. */
  1101. Vector3.prototype.subtractInPlace = function (otherVector) {
  1102. this.x -= otherVector.x;
  1103. this.y -= otherVector.y;
  1104. this.z -= otherVector.z;
  1105. return this;
  1106. };
  1107. /**
  1108. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1109. */
  1110. Vector3.prototype.subtract = function (otherVector) {
  1111. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1112. };
  1113. /**
  1114. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1115. * Returns the current Vector3.
  1116. */
  1117. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1118. result.x = this.x - otherVector.x;
  1119. result.y = this.y - otherVector.y;
  1120. result.z = this.z - otherVector.z;
  1121. return this;
  1122. };
  1123. /**
  1124. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1125. */
  1126. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1127. return new Vector3(this.x - x, this.y - y, this.z - z);
  1128. };
  1129. /**
  1130. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1131. * Returns the current Vector3.
  1132. */
  1133. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1134. result.x = this.x - x;
  1135. result.y = this.y - y;
  1136. result.z = this.z - z;
  1137. return this;
  1138. };
  1139. /**
  1140. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1141. */
  1142. Vector3.prototype.negate = function () {
  1143. return new Vector3(-this.x, -this.y, -this.z);
  1144. };
  1145. /**
  1146. * Multiplies the Vector3 coordinates by the float "scale".
  1147. * Returns the updated Vector3.
  1148. */
  1149. Vector3.prototype.scaleInPlace = function (scale) {
  1150. this.x *= scale;
  1151. this.y *= scale;
  1152. this.z *= scale;
  1153. return this;
  1154. };
  1155. /**
  1156. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1157. */
  1158. Vector3.prototype.scale = function (scale) {
  1159. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1160. };
  1161. /**
  1162. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1163. * Returns the current Vector3.
  1164. */
  1165. Vector3.prototype.scaleToRef = function (scale, result) {
  1166. result.x = this.x * scale;
  1167. result.y = this.y * scale;
  1168. result.z = this.z * scale;
  1169. return this;
  1170. };
  1171. /**
  1172. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1173. */
  1174. Vector3.prototype.equals = function (otherVector) {
  1175. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1176. };
  1177. /**
  1178. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1179. */
  1180. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1181. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1182. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1183. };
  1184. /**
  1185. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1186. */
  1187. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1188. return this.x === x && this.y === y && this.z === z;
  1189. };
  1190. /**
  1191. * Muliplies the current Vector3 coordinates by the passed ones.
  1192. * Returns the updated Vector3.
  1193. */
  1194. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1195. this.x *= otherVector.x;
  1196. this.y *= otherVector.y;
  1197. this.z *= otherVector.z;
  1198. return this;
  1199. };
  1200. /**
  1201. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1202. */
  1203. Vector3.prototype.multiply = function (otherVector) {
  1204. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1205. };
  1206. /**
  1207. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1208. * Returns the current Vector3.
  1209. */
  1210. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1211. result.x = this.x * otherVector.x;
  1212. result.y = this.y * otherVector.y;
  1213. result.z = this.z * otherVector.z;
  1214. return this;
  1215. };
  1216. /**
  1217. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1218. */
  1219. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1220. return new Vector3(this.x * x, this.y * y, this.z * z);
  1221. };
  1222. /**
  1223. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1224. */
  1225. Vector3.prototype.divide = function (otherVector) {
  1226. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1227. };
  1228. /**
  1229. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1230. * Returns the current Vector3.
  1231. */
  1232. Vector3.prototype.divideToRef = function (otherVector, result) {
  1233. result.x = this.x / otherVector.x;
  1234. result.y = this.y / otherVector.y;
  1235. result.z = this.z / otherVector.z;
  1236. return this;
  1237. };
  1238. /**
  1239. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1240. * Returns the updated Vector3.
  1241. */
  1242. Vector3.prototype.MinimizeInPlace = function (other) {
  1243. if (other.x < this.x)
  1244. this.x = other.x;
  1245. if (other.y < this.y)
  1246. this.y = other.y;
  1247. if (other.z < this.z)
  1248. this.z = other.z;
  1249. return this;
  1250. };
  1251. /**
  1252. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1253. * Returns the updated Vector3.
  1254. */
  1255. Vector3.prototype.MaximizeInPlace = function (other) {
  1256. if (other.x > this.x)
  1257. this.x = other.x;
  1258. if (other.y > this.y)
  1259. this.y = other.y;
  1260. if (other.z > this.z)
  1261. this.z = other.z;
  1262. return this;
  1263. };
  1264. // Properties
  1265. /**
  1266. * Returns the length of the Vector3 (float).
  1267. */
  1268. Vector3.prototype.length = function () {
  1269. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1270. };
  1271. /**
  1272. * Returns the squared length of the Vector3 (float).
  1273. */
  1274. Vector3.prototype.lengthSquared = function () {
  1275. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1276. };
  1277. // Methods
  1278. /**
  1279. * Normalize the current Vector3.
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.normalize = function () {
  1283. var len = this.length();
  1284. if (len === 0 || len === 1.0)
  1285. return this;
  1286. var num = 1.0 / len;
  1287. this.x *= num;
  1288. this.y *= num;
  1289. this.z *= num;
  1290. return this;
  1291. };
  1292. /**
  1293. * Returns a new Vector3 copied from the current Vector3.
  1294. */
  1295. Vector3.prototype.clone = function () {
  1296. return new Vector3(this.x, this.y, this.z);
  1297. };
  1298. /**
  1299. * Copies the passed vector coordinates to the current Vector3 ones.
  1300. * Returns the updated Vector3.
  1301. */
  1302. Vector3.prototype.copyFrom = function (source) {
  1303. this.x = source.x;
  1304. this.y = source.y;
  1305. this.z = source.z;
  1306. return this;
  1307. };
  1308. /**
  1309. * Copies the passed floats to the current Vector3 coordinates.
  1310. * Returns the updated Vector3.
  1311. */
  1312. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1313. this.x = x;
  1314. this.y = y;
  1315. this.z = z;
  1316. return this;
  1317. };
  1318. /**
  1319. * Copies the passed floats to the current Vector3 coordinates.
  1320. * Returns the updated Vector3.
  1321. */
  1322. Vector3.prototype.set = function (x, y, z) {
  1323. return this.copyFromFloats(x, y, z);
  1324. };
  1325. // Statics
  1326. /**
  1327. *
  1328. */
  1329. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1330. var d0 = Vector3.Dot(vector0, axis) - size;
  1331. var d1 = Vector3.Dot(vector1, axis) - size;
  1332. var s = d0 / (d0 - d1);
  1333. return s;
  1334. };
  1335. /**
  1336. * Returns a new Vector3 set from the index "offset" of the passed array.
  1337. */
  1338. Vector3.FromArray = function (array, offset) {
  1339. if (!offset) {
  1340. offset = 0;
  1341. }
  1342. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1343. };
  1344. /**
  1345. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1346. * This function is deprecated. Use FromArray instead.
  1347. */
  1348. Vector3.FromFloatArray = function (array, offset) {
  1349. return Vector3.FromArray(array, offset);
  1350. };
  1351. /**
  1352. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1353. */
  1354. Vector3.FromArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. };
  1359. /**
  1360. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1361. * This function is deprecated. Use FromArrayToRef instead.
  1362. */
  1363. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1364. return Vector3.FromArrayToRef(array, offset, result);
  1365. };
  1366. /**
  1367. * Sets the passed vector "result" with the passed floats.
  1368. */
  1369. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1370. result.x = x;
  1371. result.y = y;
  1372. result.z = z;
  1373. };
  1374. /**
  1375. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1376. */
  1377. Vector3.Zero = function () {
  1378. return new Vector3(0.0, 0.0, 0.0);
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1382. */
  1383. Vector3.Up = function () {
  1384. return new Vector3(0.0, 1.0, 0.0);
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1388. */
  1389. Vector3.Forward = function () {
  1390. return new Vector3(0.0, 0.0, 1.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1394. */
  1395. Vector3.Right = function () {
  1396. return new Vector3(1.0, 0.0, 0.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1400. */
  1401. Vector3.Left = function () {
  1402. return new Vector3(-1.0, 0.0, 0.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1406. * This method computes tranformed coordinates only, not transformed direction vectors.
  1407. */
  1408. Vector3.TransformCoordinates = function (vector, transformation) {
  1409. var result = Vector3.Zero();
  1410. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1411. return result;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1418. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1419. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1420. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1421. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1422. result.x = x / w;
  1423. result.y = y / w;
  1424. result.z = z / w;
  1425. };
  1426. /**
  1427. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1428. * This method computes tranformed coordinates only, not transformed direction vectors.
  1429. */
  1430. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1431. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1432. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1433. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1434. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1435. result.x = rx / rw;
  1436. result.y = ry / rw;
  1437. result.z = rz / rw;
  1438. };
  1439. /**
  1440. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1441. * This methods computes transformed normalized direction vectors only.
  1442. */
  1443. Vector3.TransformNormal = function (vector, transformation) {
  1444. var result = Vector3.Zero();
  1445. Vector3.TransformNormalToRef(vector, transformation, result);
  1446. return result;
  1447. };
  1448. /**
  1449. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1450. * This methods computes transformed normalized direction vectors only.
  1451. */
  1452. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1453. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1454. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1455. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1456. result.x = x;
  1457. result.y = y;
  1458. result.z = z;
  1459. };
  1460. /**
  1461. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1462. * This methods computes transformed normalized direction vectors only.
  1463. */
  1464. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1465. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1466. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1467. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1468. };
  1469. /**
  1470. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1471. */
  1472. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1473. var squared = amount * amount;
  1474. var cubed = amount * squared;
  1475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1481. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1482. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1483. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1484. return new Vector3(x, y, z);
  1485. };
  1486. /**
  1487. * 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".
  1488. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1489. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1490. */
  1491. Vector3.Clamp = function (value, min, max) {
  1492. var x = value.x;
  1493. x = (x > max.x) ? max.x : x;
  1494. x = (x < min.x) ? min.x : x;
  1495. var y = value.y;
  1496. y = (y > max.y) ? max.y : y;
  1497. y = (y < min.y) ? min.y : y;
  1498. var z = value.z;
  1499. z = (z > max.z) ? max.z : z;
  1500. z = (z < min.z) ? min.z : z;
  1501. return new Vector3(x, y, z);
  1502. };
  1503. /**
  1504. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1505. */
  1506. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1507. var squared = amount * amount;
  1508. var cubed = amount * squared;
  1509. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1510. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1511. var part3 = (cubed - (2.0 * squared)) + amount;
  1512. var part4 = cubed - squared;
  1513. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1514. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1515. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1516. return new Vector3(x, y, z);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1520. */
  1521. Vector3.Lerp = function (start, end, amount) {
  1522. var result = new Vector3(0, 0, 0);
  1523. Vector3.LerpToRef(start, end, amount, result);
  1524. return result;
  1525. };
  1526. /**
  1527. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1528. */
  1529. Vector3.LerpToRef = function (start, end, amount, result) {
  1530. result.x = start.x + ((end.x - start.x) * amount);
  1531. result.y = start.y + ((end.y - start.y) * amount);
  1532. result.z = start.z + ((end.z - start.z) * amount);
  1533. };
  1534. /**
  1535. * Returns the dot product (float) between the vectors "left" and "right".
  1536. */
  1537. Vector3.Dot = function (left, right) {
  1538. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1539. };
  1540. /**
  1541. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1542. * The cross product is then orthogonal to both "left" and "right".
  1543. */
  1544. Vector3.Cross = function (left, right) {
  1545. var result = Vector3.Zero();
  1546. Vector3.CrossToRef(left, right, result);
  1547. return result;
  1548. };
  1549. /**
  1550. * Sets the passed vector "result" with the cross product of "left" and "right".
  1551. * The cross product is then orthogonal to both "left" and "right".
  1552. */
  1553. Vector3.CrossToRef = function (left, right, result) {
  1554. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1555. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1556. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1557. result.copyFrom(MathTmp.Vector3[0]);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 as the normalization of the passed vector.
  1561. */
  1562. Vector3.Normalize = function (vector) {
  1563. var result = Vector3.Zero();
  1564. Vector3.NormalizeToRef(vector, result);
  1565. return result;
  1566. };
  1567. /**
  1568. * Sets the passed vector "result" with the normalization of the passed first vector.
  1569. */
  1570. Vector3.NormalizeToRef = function (vector, result) {
  1571. result.copyFrom(vector);
  1572. result.normalize();
  1573. };
  1574. Vector3.Project = function (vector, world, transform, viewport) {
  1575. var cw = viewport.width;
  1576. var ch = viewport.height;
  1577. var cx = viewport.x;
  1578. var cy = viewport.y;
  1579. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1580. 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);
  1581. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1582. world.multiplyToRef(transform, matrix);
  1583. matrix.multiplyToRef(viewportMatrix, matrix);
  1584. return Vector3.TransformCoordinates(vector, matrix);
  1585. };
  1586. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1587. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1588. world.multiplyToRef(transform, matrix);
  1589. matrix.invert();
  1590. source.x = source.x / viewportWidth * 2 - 1;
  1591. source.y = -(source.y / viewportHeight * 2 - 1);
  1592. var vector = Vector3.TransformCoordinates(source, matrix);
  1593. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1594. if (MathTools.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1600. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1601. world.multiplyToRef(view, matrix);
  1602. matrix.multiplyToRef(projection, matrix);
  1603. matrix.invert();
  1604. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1605. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1606. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1607. if (MathTools.WithinEpsilon(num, 1.0)) {
  1608. vector = vector.scale(1.0 / num);
  1609. }
  1610. return vector;
  1611. };
  1612. Vector3.Minimize = function (left, right) {
  1613. var min = left.clone();
  1614. min.MinimizeInPlace(right);
  1615. return min;
  1616. };
  1617. Vector3.Maximize = function (left, right) {
  1618. var max = left.clone();
  1619. max.MaximizeInPlace(right);
  1620. return max;
  1621. };
  1622. /**
  1623. * Returns the distance (float) between the vectors "value1" and "value2".
  1624. */
  1625. Vector3.Distance = function (value1, value2) {
  1626. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1627. };
  1628. /**
  1629. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1630. */
  1631. Vector3.DistanceSquared = function (value1, value2) {
  1632. var x = value1.x - value2.x;
  1633. var y = value1.y - value2.y;
  1634. var z = value1.z - value2.z;
  1635. return (x * x) + (y * y) + (z * z);
  1636. };
  1637. /**
  1638. * Returns a new Vector3 located at the center between "value1" and "value2".
  1639. */
  1640. Vector3.Center = function (value1, value2) {
  1641. var center = value1.add(value2);
  1642. center.scaleInPlace(0.5);
  1643. return center;
  1644. };
  1645. /**
  1646. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1647. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1648. * to something in order to rotate it from its local system to the given target system.
  1649. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1650. * Returns a new Vector3.
  1651. */
  1652. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1653. var rotation = Vector3.Zero();
  1654. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1655. return rotation;
  1656. };
  1657. /**
  1658. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1659. */
  1660. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1661. var quat = MathTmp.Quaternion[0];
  1662. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1663. quat.toEulerAnglesToRef(ref);
  1664. };
  1665. return Vector3;
  1666. }());
  1667. BABYLON.Vector3 = Vector3;
  1668. //Vector4 class created for EulerAngle class conversion to Quaternion
  1669. var Vector4 = (function () {
  1670. /**
  1671. * Creates a Vector4 object from the passed floats.
  1672. */
  1673. function Vector4(x, y, z, w) {
  1674. this.x = x;
  1675. this.y = y;
  1676. this.z = z;
  1677. this.w = w;
  1678. }
  1679. /**
  1680. * Returns the string with the Vector4 coordinates.
  1681. */
  1682. Vector4.prototype.toString = function () {
  1683. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1684. };
  1685. /**
  1686. * Returns the string "Vector4".
  1687. */
  1688. Vector4.prototype.getClassName = function () {
  1689. return "Vector4";
  1690. };
  1691. /**
  1692. * Returns the Vector4 hash code.
  1693. */
  1694. Vector4.prototype.getHashCode = function () {
  1695. var hash = this.x || 0;
  1696. hash = (hash * 397) ^ (this.y || 0);
  1697. hash = (hash * 397) ^ (this.z || 0);
  1698. hash = (hash * 397) ^ (this.w || 0);
  1699. return hash;
  1700. };
  1701. // Operators
  1702. /**
  1703. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1704. */
  1705. Vector4.prototype.asArray = function () {
  1706. var result = [];
  1707. this.toArray(result, 0);
  1708. return result;
  1709. };
  1710. /**
  1711. * Populates the passed array from the passed index with the Vector4 coordinates.
  1712. * Returns the Vector4.
  1713. */
  1714. Vector4.prototype.toArray = function (array, index) {
  1715. if (index === undefined) {
  1716. index = 0;
  1717. }
  1718. array[index] = this.x;
  1719. array[index + 1] = this.y;
  1720. array[index + 2] = this.z;
  1721. array[index + 3] = this.w;
  1722. return this;
  1723. };
  1724. /**
  1725. * Adds the passed vector to the current Vector4.
  1726. * Returns the updated Vector4.
  1727. */
  1728. Vector4.prototype.addInPlace = function (otherVector) {
  1729. this.x += otherVector.x;
  1730. this.y += otherVector.y;
  1731. this.z += otherVector.z;
  1732. this.w += otherVector.w;
  1733. return this;
  1734. };
  1735. /**
  1736. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1737. */
  1738. Vector4.prototype.add = function (otherVector) {
  1739. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1740. };
  1741. /**
  1742. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1743. * Returns the current Vector4.
  1744. */
  1745. Vector4.prototype.addToRef = function (otherVector, result) {
  1746. result.x = this.x + otherVector.x;
  1747. result.y = this.y + otherVector.y;
  1748. result.z = this.z + otherVector.z;
  1749. result.w = this.w + otherVector.w;
  1750. return this;
  1751. };
  1752. /**
  1753. * Subtract in place the passed vector from the current Vector4.
  1754. * Returns the updated Vector4.
  1755. */
  1756. Vector4.prototype.subtractInPlace = function (otherVector) {
  1757. this.x -= otherVector.x;
  1758. this.y -= otherVector.y;
  1759. this.z -= otherVector.z;
  1760. this.w -= otherVector.w;
  1761. return this;
  1762. };
  1763. /**
  1764. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1765. */
  1766. Vector4.prototype.subtract = function (otherVector) {
  1767. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1768. };
  1769. /**
  1770. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1771. * Returns the current Vector4.
  1772. */
  1773. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1774. result.x = this.x - otherVector.x;
  1775. result.y = this.y - otherVector.y;
  1776. result.z = this.z - otherVector.z;
  1777. result.w = this.w - otherVector.w;
  1778. return this;
  1779. };
  1780. /**
  1781. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1782. */
  1783. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1784. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1785. };
  1786. /**
  1787. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1788. * Returns the current Vector4.
  1789. */
  1790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1791. result.x = this.x - x;
  1792. result.y = this.y - y;
  1793. result.z = this.z - z;
  1794. result.w = this.w - w;
  1795. return this;
  1796. };
  1797. /**
  1798. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1799. */
  1800. Vector4.prototype.negate = function () {
  1801. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1802. };
  1803. /**
  1804. * Multiplies the current Vector4 coordinates by scale (float).
  1805. * Returns the updated Vector4.
  1806. */
  1807. Vector4.prototype.scaleInPlace = function (scale) {
  1808. this.x *= scale;
  1809. this.y *= scale;
  1810. this.z *= scale;
  1811. this.w *= scale;
  1812. return this;
  1813. };
  1814. /**
  1815. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1816. */
  1817. Vector4.prototype.scale = function (scale) {
  1818. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1819. };
  1820. /**
  1821. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1822. * Returns the current Vector4.
  1823. */
  1824. Vector4.prototype.scaleToRef = function (scale, result) {
  1825. result.x = this.x * scale;
  1826. result.y = this.y * scale;
  1827. result.z = this.z * scale;
  1828. result.w = this.w * scale;
  1829. return this;
  1830. };
  1831. /**
  1832. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1833. */
  1834. Vector4.prototype.equals = function (otherVector) {
  1835. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1836. };
  1837. /**
  1838. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1839. */
  1840. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1841. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1842. return otherVector
  1843. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1844. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1845. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1846. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1847. };
  1848. /**
  1849. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1850. */
  1851. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1852. return this.x === x && this.y === y && this.z === z && this.w === w;
  1853. };
  1854. /**
  1855. * Multiplies in place the current Vector4 by the passed one.
  1856. * Returns the updated Vector4.
  1857. */
  1858. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1859. this.x *= otherVector.x;
  1860. this.y *= otherVector.y;
  1861. this.z *= otherVector.z;
  1862. this.w *= otherVector.w;
  1863. return this;
  1864. };
  1865. /**
  1866. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1867. */
  1868. Vector4.prototype.multiply = function (otherVector) {
  1869. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1870. };
  1871. /**
  1872. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1873. * Returns the current Vector4.
  1874. */
  1875. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1876. result.x = this.x * otherVector.x;
  1877. result.y = this.y * otherVector.y;
  1878. result.z = this.z * otherVector.z;
  1879. result.w = this.w * otherVector.w;
  1880. return this;
  1881. };
  1882. /**
  1883. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1884. */
  1885. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1886. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1887. };
  1888. /**
  1889. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1890. */
  1891. Vector4.prototype.divide = function (otherVector) {
  1892. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1893. };
  1894. /**
  1895. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1896. * Returns the current Vector4.
  1897. */
  1898. Vector4.prototype.divideToRef = function (otherVector, result) {
  1899. result.x = this.x / otherVector.x;
  1900. result.y = this.y / otherVector.y;
  1901. result.z = this.z / otherVector.z;
  1902. result.w = this.w / otherVector.w;
  1903. return this;
  1904. };
  1905. /**
  1906. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1907. */
  1908. Vector4.prototype.MinimizeInPlace = function (other) {
  1909. if (other.x < this.x)
  1910. this.x = other.x;
  1911. if (other.y < this.y)
  1912. this.y = other.y;
  1913. if (other.z < this.z)
  1914. this.z = other.z;
  1915. if (other.w < this.w)
  1916. this.w = other.w;
  1917. return this;
  1918. };
  1919. /**
  1920. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1921. */
  1922. Vector4.prototype.MaximizeInPlace = function (other) {
  1923. if (other.x > this.x)
  1924. this.x = other.x;
  1925. if (other.y > this.y)
  1926. this.y = other.y;
  1927. if (other.z > this.z)
  1928. this.z = other.z;
  1929. if (other.w > this.w)
  1930. this.w = other.w;
  1931. return this;
  1932. };
  1933. // Properties
  1934. /**
  1935. * Returns the Vector4 length (float).
  1936. */
  1937. Vector4.prototype.length = function () {
  1938. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1939. };
  1940. /**
  1941. * Returns the Vector4 squared length (float).
  1942. */
  1943. Vector4.prototype.lengthSquared = function () {
  1944. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1945. };
  1946. // Methods
  1947. /**
  1948. * Normalizes in place the Vector4.
  1949. * Returns the updated Vector4.
  1950. */
  1951. Vector4.prototype.normalize = function () {
  1952. var len = this.length();
  1953. if (len === 0)
  1954. return this;
  1955. var num = 1.0 / len;
  1956. this.x *= num;
  1957. this.y *= num;
  1958. this.z *= num;
  1959. this.w *= num;
  1960. return this;
  1961. };
  1962. /**
  1963. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1964. */
  1965. Vector4.prototype.toVector3 = function () {
  1966. return new Vector3(this.x, this.y, this.z);
  1967. };
  1968. /**
  1969. * Returns a new Vector4 copied from the current one.
  1970. */
  1971. Vector4.prototype.clone = function () {
  1972. return new Vector4(this.x, this.y, this.z, this.w);
  1973. };
  1974. /**
  1975. * Updates the current Vector4 with the passed one coordinates.
  1976. * Returns the updated Vector4.
  1977. */
  1978. Vector4.prototype.copyFrom = function (source) {
  1979. this.x = source.x;
  1980. this.y = source.y;
  1981. this.z = source.z;
  1982. this.w = source.w;
  1983. return this;
  1984. };
  1985. /**
  1986. * Updates the current Vector4 coordinates with the passed floats.
  1987. * Returns the updated Vector4.
  1988. */
  1989. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1990. this.x = x;
  1991. this.y = y;
  1992. this.z = z;
  1993. this.w = w;
  1994. return this;
  1995. };
  1996. /**
  1997. * Updates the current Vector4 coordinates with the passed floats.
  1998. * Returns the updated Vector4.
  1999. */
  2000. Vector4.prototype.set = function (x, y, z, w) {
  2001. return this.copyFromFloats(x, y, z, w);
  2002. };
  2003. // Statics
  2004. /**
  2005. * Returns a new Vector4 set from the starting index of the passed array.
  2006. */
  2007. Vector4.FromArray = function (array, offset) {
  2008. if (!offset) {
  2009. offset = 0;
  2010. }
  2011. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2012. };
  2013. /**
  2014. * Updates the passed vector "result" from the starting index of the passed array.
  2015. */
  2016. Vector4.FromArrayToRef = function (array, offset, result) {
  2017. result.x = array[offset];
  2018. result.y = array[offset + 1];
  2019. result.z = array[offset + 2];
  2020. result.w = array[offset + 3];
  2021. };
  2022. /**
  2023. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2024. */
  2025. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2026. Vector4.FromArrayToRef(array, offset, result);
  2027. };
  2028. /**
  2029. * Updates the passed vector "result" coordinates from the passed floats.
  2030. */
  2031. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2032. result.x = x;
  2033. result.y = y;
  2034. result.z = z;
  2035. result.w = w;
  2036. };
  2037. /**
  2038. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2039. */
  2040. Vector4.Zero = function () {
  2041. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2042. };
  2043. /**
  2044. * Returns a new normalized Vector4 from the passed one.
  2045. */
  2046. Vector4.Normalize = function (vector) {
  2047. var result = Vector4.Zero();
  2048. Vector4.NormalizeToRef(vector, result);
  2049. return result;
  2050. };
  2051. /**
  2052. * Updates the passed vector "result" from the normalization of the passed one.
  2053. */
  2054. Vector4.NormalizeToRef = function (vector, result) {
  2055. result.copyFrom(vector);
  2056. result.normalize();
  2057. };
  2058. Vector4.Minimize = function (left, right) {
  2059. var min = left.clone();
  2060. min.MinimizeInPlace(right);
  2061. return min;
  2062. };
  2063. Vector4.Maximize = function (left, right) {
  2064. var max = left.clone();
  2065. max.MaximizeInPlace(right);
  2066. return max;
  2067. };
  2068. /**
  2069. * Returns the distance (float) between the vectors "value1" and "value2".
  2070. */
  2071. Vector4.Distance = function (value1, value2) {
  2072. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2073. };
  2074. /**
  2075. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2076. */
  2077. Vector4.DistanceSquared = function (value1, value2) {
  2078. var x = value1.x - value2.x;
  2079. var y = value1.y - value2.y;
  2080. var z = value1.z - value2.z;
  2081. var w = value1.w - value2.w;
  2082. return (x * x) + (y * y) + (z * z) + (w * w);
  2083. };
  2084. /**
  2085. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2086. */
  2087. Vector4.Center = function (value1, value2) {
  2088. var center = value1.add(value2);
  2089. center.scaleInPlace(0.5);
  2090. return center;
  2091. };
  2092. /**
  2093. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2094. * This methods computes transformed normalized direction vectors only.
  2095. */
  2096. Vector4.TransformNormal = function (vector, transformation) {
  2097. var result = Vector4.Zero();
  2098. Vector4.TransformNormalToRef(vector, transformation, result);
  2099. return result;
  2100. };
  2101. /**
  2102. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2103. * This methods computes transformed normalized direction vectors only.
  2104. */
  2105. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2106. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2107. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2108. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2109. result.x = x;
  2110. result.y = y;
  2111. result.z = z;
  2112. result.w = vector.w;
  2113. };
  2114. /**
  2115. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2116. * This methods computes transformed normalized direction vectors only.
  2117. */
  2118. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2119. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2120. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2121. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2122. result.w = w;
  2123. };
  2124. return Vector4;
  2125. }());
  2126. BABYLON.Vector4 = Vector4;
  2127. var Size = (function () {
  2128. /**
  2129. * Creates a Size object from the passed width and height (floats).
  2130. */
  2131. function Size(width, height) {
  2132. this.width = width;
  2133. this.height = height;
  2134. }
  2135. // Returns a string with the Size width and height.
  2136. Size.prototype.toString = function () {
  2137. return "{W: " + this.width + ", H: " + this.height + "}";
  2138. };
  2139. /**
  2140. * Returns the string "Size"
  2141. */
  2142. Size.prototype.getClassName = function () {
  2143. return "Size";
  2144. };
  2145. /**
  2146. * Returns the Size hash code.
  2147. */
  2148. Size.prototype.getHashCode = function () {
  2149. var hash = this.width || 0;
  2150. hash = (hash * 397) ^ (this.height || 0);
  2151. return hash;
  2152. };
  2153. /**
  2154. * Updates the current size from the passed one.
  2155. * Returns the updated Size.
  2156. */
  2157. Size.prototype.copyFrom = function (src) {
  2158. this.width = src.width;
  2159. this.height = src.height;
  2160. };
  2161. /**
  2162. * Updates in place the current Size from the passed floats.
  2163. * Returns the updated Size.
  2164. */
  2165. Size.prototype.copyFromFloats = function (width, height) {
  2166. this.width = width;
  2167. this.height = height;
  2168. return this;
  2169. };
  2170. /**
  2171. * Updates in place the current Size from the passed floats.
  2172. * Returns the updated Size.
  2173. */
  2174. Size.prototype.set = function (width, height) {
  2175. return this.copyFromFloats(width, height);
  2176. };
  2177. /**
  2178. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2179. */
  2180. Size.prototype.multiplyByFloats = function (w, h) {
  2181. return new Size(this.width * w, this.height * h);
  2182. };
  2183. /**
  2184. * Returns a new Size copied from the passed one.
  2185. */
  2186. Size.prototype.clone = function () {
  2187. return new Size(this.width, this.height);
  2188. };
  2189. /**
  2190. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2191. */
  2192. Size.prototype.equals = function (other) {
  2193. if (!other) {
  2194. return false;
  2195. }
  2196. return (this.width === other.width) && (this.height === other.height);
  2197. };
  2198. Object.defineProperty(Size.prototype, "surface", {
  2199. /**
  2200. * Returns the surface of the Size : width * height (float).
  2201. */
  2202. get: function () {
  2203. return this.width * this.height;
  2204. },
  2205. enumerable: true,
  2206. configurable: true
  2207. });
  2208. /**
  2209. * Returns a new Size set to (0.0, 0.0)
  2210. */
  2211. Size.Zero = function () {
  2212. return new Size(0.0, 0.0);
  2213. };
  2214. /**
  2215. * Returns a new Size set as the addition result of the current Size and the passed one.
  2216. */
  2217. Size.prototype.add = function (otherSize) {
  2218. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2223. */
  2224. Size.prototype.subtract = function (otherSize) {
  2225. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2226. return r;
  2227. };
  2228. /**
  2229. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2230. */
  2231. Size.Lerp = function (start, end, amount) {
  2232. var w = start.width + ((end.width - start.width) * amount);
  2233. var h = start.height + ((end.height - start.height) * amount);
  2234. return new Size(w, h);
  2235. };
  2236. return Size;
  2237. }());
  2238. BABYLON.Size = Size;
  2239. var Quaternion = (function () {
  2240. /**
  2241. * Creates a new Quaternion from the passed floats.
  2242. */
  2243. function Quaternion(x, y, z, w) {
  2244. if (x === void 0) { x = 0.0; }
  2245. if (y === void 0) { y = 0.0; }
  2246. if (z === void 0) { z = 0.0; }
  2247. if (w === void 0) { w = 1.0; }
  2248. this.x = x;
  2249. this.y = y;
  2250. this.z = z;
  2251. this.w = w;
  2252. }
  2253. /**
  2254. * Returns a string with the Quaternion coordinates.
  2255. */
  2256. Quaternion.prototype.toString = function () {
  2257. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2258. };
  2259. /**
  2260. * Returns the string "Quaternion".
  2261. */
  2262. Quaternion.prototype.getClassName = function () {
  2263. return "Quaternion";
  2264. };
  2265. /**
  2266. * Returns the Quaternion hash code.
  2267. */
  2268. Quaternion.prototype.getHashCode = function () {
  2269. var hash = this.x || 0;
  2270. hash = (hash * 397) ^ (this.y || 0);
  2271. hash = (hash * 397) ^ (this.z || 0);
  2272. hash = (hash * 397) ^ (this.w || 0);
  2273. return hash;
  2274. };
  2275. /**
  2276. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2277. */
  2278. Quaternion.prototype.asArray = function () {
  2279. return [this.x, this.y, this.z, this.w];
  2280. };
  2281. /**
  2282. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2283. */
  2284. Quaternion.prototype.equals = function (otherQuaternion) {
  2285. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2286. };
  2287. /**
  2288. * Returns a new Quaternion copied from the current one.
  2289. */
  2290. Quaternion.prototype.clone = function () {
  2291. return new Quaternion(this.x, this.y, this.z, this.w);
  2292. };
  2293. /**
  2294. * Updates the current Quaternion from the passed one coordinates.
  2295. * Returns the updated Quaterion.
  2296. */
  2297. Quaternion.prototype.copyFrom = function (other) {
  2298. this.x = other.x;
  2299. this.y = other.y;
  2300. this.z = other.z;
  2301. this.w = other.w;
  2302. return this;
  2303. };
  2304. /**
  2305. * Updates the current Quaternion from the passed float coordinates.
  2306. * Returns the updated Quaterion.
  2307. */
  2308. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2309. this.x = x;
  2310. this.y = y;
  2311. this.z = z;
  2312. this.w = w;
  2313. return this;
  2314. };
  2315. /**
  2316. * Updates the current Quaternion from the passed float coordinates.
  2317. * Returns the updated Quaterion.
  2318. */
  2319. Quaternion.prototype.set = function (x, y, z, w) {
  2320. return this.copyFromFloats(x, y, z, w);
  2321. };
  2322. /**
  2323. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2324. */
  2325. Quaternion.prototype.add = function (other) {
  2326. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2327. };
  2328. /**
  2329. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2330. */
  2331. Quaternion.prototype.subtract = function (other) {
  2332. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2333. };
  2334. /**
  2335. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2336. */
  2337. Quaternion.prototype.scale = function (value) {
  2338. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2339. };
  2340. /**
  2341. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2342. */
  2343. Quaternion.prototype.multiply = function (q1) {
  2344. var result = new Quaternion(0, 0, 0, 1.0);
  2345. this.multiplyToRef(q1, result);
  2346. return result;
  2347. };
  2348. /**
  2349. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2350. * Returns the current Quaternion.
  2351. */
  2352. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2353. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2354. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2355. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2356. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2357. result.copyFromFloats(x, y, z, w);
  2358. return this;
  2359. };
  2360. /**
  2361. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2362. * Returns the updated Quaternion.
  2363. */
  2364. Quaternion.prototype.multiplyInPlace = function (q1) {
  2365. this.multiplyToRef(q1, this);
  2366. return this;
  2367. };
  2368. /**
  2369. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2370. * Returns the current Quaternion.
  2371. */
  2372. Quaternion.prototype.conjugateToRef = function (ref) {
  2373. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2374. return this;
  2375. };
  2376. /**
  2377. * Conjugates in place the current Quaternion.
  2378. * Returns the updated Quaternion.
  2379. */
  2380. Quaternion.prototype.conjugateInPlace = function () {
  2381. this.x *= -1;
  2382. this.y *= -1;
  2383. this.z *= -1;
  2384. return this;
  2385. };
  2386. /**
  2387. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2388. */
  2389. Quaternion.prototype.conjugate = function () {
  2390. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2391. return result;
  2392. };
  2393. /**
  2394. * Returns the Quaternion length (float).
  2395. */
  2396. Quaternion.prototype.length = function () {
  2397. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2398. };
  2399. /**
  2400. * Normalize in place the current Quaternion.
  2401. * Returns the updated Quaternion.
  2402. */
  2403. Quaternion.prototype.normalize = function () {
  2404. var length = 1.0 / this.length();
  2405. this.x *= length;
  2406. this.y *= length;
  2407. this.z *= length;
  2408. this.w *= length;
  2409. return this;
  2410. };
  2411. /**
  2412. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2413. */
  2414. Quaternion.prototype.toEulerAngles = function (order) {
  2415. if (order === void 0) { order = "YZX"; }
  2416. var result = Vector3.Zero();
  2417. this.toEulerAnglesToRef(result, order);
  2418. return result;
  2419. };
  2420. /**
  2421. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2422. * Returns the current Quaternion.
  2423. */
  2424. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2425. if (order === void 0) { order = "YZX"; }
  2426. var qz = this.z;
  2427. var qx = this.x;
  2428. var qy = this.y;
  2429. var qw = this.w;
  2430. var sqw = qw * qw;
  2431. var sqz = qz * qz;
  2432. var sqx = qx * qx;
  2433. var sqy = qy * qy;
  2434. var zAxisY = qy * qz - qx * qw;
  2435. var limit = .4999999;
  2436. if (zAxisY < -limit) {
  2437. result.y = 2 * Math.atan2(qy, qw);
  2438. result.x = Math.PI / 2;
  2439. result.z = 0;
  2440. }
  2441. else if (zAxisY > limit) {
  2442. result.y = 2 * Math.atan2(qy, qw);
  2443. result.x = -Math.PI / 2;
  2444. result.z = 0;
  2445. }
  2446. else {
  2447. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2448. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2449. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2450. }
  2451. return this;
  2452. };
  2453. /**
  2454. * Updates the passed rotation matrix with the current Quaternion values.
  2455. * Returns the current Quaternion.
  2456. */
  2457. Quaternion.prototype.toRotationMatrix = function (result) {
  2458. var xx = this.x * this.x;
  2459. var yy = this.y * this.y;
  2460. var zz = this.z * this.z;
  2461. var xy = this.x * this.y;
  2462. var zw = this.z * this.w;
  2463. var zx = this.z * this.x;
  2464. var yw = this.y * this.w;
  2465. var yz = this.y * this.z;
  2466. var xw = this.x * this.w;
  2467. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2468. result.m[1] = 2.0 * (xy + zw);
  2469. result.m[2] = 2.0 * (zx - yw);
  2470. result.m[3] = 0;
  2471. result.m[4] = 2.0 * (xy - zw);
  2472. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2473. result.m[6] = 2.0 * (yz + xw);
  2474. result.m[7] = 0;
  2475. result.m[8] = 2.0 * (zx + yw);
  2476. result.m[9] = 2.0 * (yz - xw);
  2477. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2478. result.m[11] = 0;
  2479. result.m[12] = 0;
  2480. result.m[13] = 0;
  2481. result.m[14] = 0;
  2482. result.m[15] = 1.0;
  2483. result._markAsUpdated();
  2484. return this;
  2485. };
  2486. /**
  2487. * Updates the current Quaternion from the passed rotation matrix values.
  2488. * Returns the updated Quaternion.
  2489. */
  2490. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2491. Quaternion.FromRotationMatrixToRef(matrix, this);
  2492. return this;
  2493. };
  2494. // Statics
  2495. /**
  2496. * Returns a new Quaternion set from the passed rotation matrix values.
  2497. */
  2498. Quaternion.FromRotationMatrix = function (matrix) {
  2499. var result = new Quaternion();
  2500. Quaternion.FromRotationMatrixToRef(matrix, result);
  2501. return result;
  2502. };
  2503. /**
  2504. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2505. */
  2506. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2507. var data = matrix.m;
  2508. var m11 = data[0], m12 = data[4], m13 = data[8];
  2509. var m21 = data[1], m22 = data[5], m23 = data[9];
  2510. var m31 = data[2], m32 = data[6], m33 = data[10];
  2511. var trace = m11 + m22 + m33;
  2512. var s;
  2513. if (trace > 0) {
  2514. s = 0.5 / Math.sqrt(trace + 1.0);
  2515. result.w = 0.25 / s;
  2516. result.x = (m32 - m23) * s;
  2517. result.y = (m13 - m31) * s;
  2518. result.z = (m21 - m12) * s;
  2519. }
  2520. else if (m11 > m22 && m11 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2522. result.w = (m32 - m23) / s;
  2523. result.x = 0.25 * s;
  2524. result.y = (m12 + m21) / s;
  2525. result.z = (m13 + m31) / s;
  2526. }
  2527. else if (m22 > m33) {
  2528. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2529. result.w = (m13 - m31) / s;
  2530. result.x = (m12 + m21) / s;
  2531. result.y = 0.25 * s;
  2532. result.z = (m23 + m32) / s;
  2533. }
  2534. else {
  2535. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2536. result.w = (m21 - m12) / s;
  2537. result.x = (m13 + m31) / s;
  2538. result.y = (m23 + m32) / s;
  2539. result.z = 0.25 * s;
  2540. }
  2541. };
  2542. /**
  2543. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2544. */
  2545. Quaternion.Zero = function () {
  2546. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2547. };
  2548. /**
  2549. * Returns a new Quaternion as the inverted current Quaternion.
  2550. */
  2551. Quaternion.Inverse = function (q) {
  2552. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2553. };
  2554. /**
  2555. * Returns the identity Quaternion.
  2556. */
  2557. Quaternion.Identity = function () {
  2558. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2559. };
  2560. Quaternion.IsIdentity = function (quaternion) {
  2561. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2562. };
  2563. /**
  2564. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2565. */
  2566. Quaternion.RotationAxis = function (axis, angle) {
  2567. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2568. };
  2569. /**
  2570. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2571. */
  2572. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2573. var sin = Math.sin(angle / 2);
  2574. axis.normalize();
  2575. result.w = Math.cos(angle / 2);
  2576. result.x = axis.x * sin;
  2577. result.y = axis.y * sin;
  2578. result.z = axis.z * sin;
  2579. return result;
  2580. };
  2581. /**
  2582. * Retuns a new Quaternion set from the starting index of the passed array.
  2583. */
  2584. Quaternion.FromArray = function (array, offset) {
  2585. if (!offset) {
  2586. offset = 0;
  2587. }
  2588. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2589. };
  2590. /**
  2591. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2592. */
  2593. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2594. var q = new Quaternion();
  2595. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2596. return q;
  2597. };
  2598. /**
  2599. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2600. */
  2601. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2602. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2603. var halfRoll = roll * 0.5;
  2604. var halfPitch = pitch * 0.5;
  2605. var halfYaw = yaw * 0.5;
  2606. var sinRoll = Math.sin(halfRoll);
  2607. var cosRoll = Math.cos(halfRoll);
  2608. var sinPitch = Math.sin(halfPitch);
  2609. var cosPitch = Math.cos(halfPitch);
  2610. var sinYaw = Math.sin(halfYaw);
  2611. var cosYaw = Math.cos(halfYaw);
  2612. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2613. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2614. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2615. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2616. };
  2617. /**
  2618. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2619. */
  2620. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2621. var result = new Quaternion();
  2622. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2623. return result;
  2624. };
  2625. /**
  2626. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2627. */
  2628. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2629. // Produces a quaternion from Euler angles in the z-x-z orientation
  2630. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2631. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2632. var halfBeta = beta * 0.5;
  2633. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2634. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2635. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2636. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2637. };
  2638. /**
  2639. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2640. * cf to Vector3.RotationFromAxis() documentation.
  2641. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2642. */
  2643. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2644. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2645. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2646. return quat;
  2647. };
  2648. /**
  2649. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2650. * cf to Vector3.RotationFromAxis() documentation.
  2651. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2652. */
  2653. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2654. var rotMat = MathTmp.Matrix[0];
  2655. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2656. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2657. };
  2658. Quaternion.Slerp = function (left, right, amount) {
  2659. var result = Quaternion.Identity();
  2660. Quaternion.SlerpToRef(left, right, amount, result);
  2661. return result;
  2662. };
  2663. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2664. var num2;
  2665. var num3;
  2666. var num = amount;
  2667. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2668. var flag = false;
  2669. if (num4 < 0) {
  2670. flag = true;
  2671. num4 = -num4;
  2672. }
  2673. if (num4 > 0.999999) {
  2674. num3 = 1 - num;
  2675. num2 = flag ? -num : num;
  2676. }
  2677. else {
  2678. var num5 = Math.acos(num4);
  2679. var num6 = (1.0 / Math.sin(num5));
  2680. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2681. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2682. }
  2683. result.x = (num3 * left.x) + (num2 * right.x);
  2684. result.y = (num3 * left.y) + (num2 * right.y);
  2685. result.z = (num3 * left.z) + (num2 * right.z);
  2686. result.w = (num3 * left.w) + (num2 * right.w);
  2687. };
  2688. /**
  2689. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2690. */
  2691. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2692. var squared = amount * amount;
  2693. var cubed = amount * squared;
  2694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2696. var part3 = (cubed - (2.0 * squared)) + amount;
  2697. var part4 = cubed - squared;
  2698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2701. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2702. return new Quaternion(x, y, z, w);
  2703. };
  2704. return Quaternion;
  2705. }());
  2706. BABYLON.Quaternion = Quaternion;
  2707. var Matrix = (function () {
  2708. function Matrix() {
  2709. this.m = new Float32Array(16);
  2710. this._markAsUpdated();
  2711. }
  2712. Matrix.prototype._markAsUpdated = function () {
  2713. this.updateFlag = Matrix._updateFlagSeed++;
  2714. };
  2715. // Properties
  2716. /**
  2717. * Boolean : True is the matrix is the identity matrix
  2718. */
  2719. Matrix.prototype.isIdentity = function () {
  2720. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2721. return false;
  2722. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2726. return false;
  2727. return true;
  2728. };
  2729. /**
  2730. * Returns the matrix determinant (float).
  2731. */
  2732. Matrix.prototype.determinant = function () {
  2733. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2734. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2735. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2736. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2737. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2738. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2739. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2740. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2741. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2742. };
  2743. // Methods
  2744. /**
  2745. * Returns the matrix underlying array.
  2746. */
  2747. Matrix.prototype.toArray = function () {
  2748. return this.m;
  2749. };
  2750. /**
  2751. * Returns the matrix underlying array.
  2752. */
  2753. Matrix.prototype.asArray = function () {
  2754. return this.toArray();
  2755. };
  2756. /**
  2757. * Inverts in place the Matrix.
  2758. * Returns the Matrix inverted.
  2759. */
  2760. Matrix.prototype.invert = function () {
  2761. this.invertToRef(this);
  2762. return this;
  2763. };
  2764. /**
  2765. * Sets all the matrix elements to zero.
  2766. * Returns the Matrix.
  2767. */
  2768. Matrix.prototype.reset = function () {
  2769. for (var index = 0; index < 16; index++) {
  2770. this.m[index] = 0.0;
  2771. }
  2772. this._markAsUpdated();
  2773. return this;
  2774. };
  2775. /**
  2776. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2777. */
  2778. Matrix.prototype.add = function (other) {
  2779. var result = new Matrix();
  2780. this.addToRef(other, result);
  2781. return result;
  2782. };
  2783. /**
  2784. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2785. * Returns the Matrix.
  2786. */
  2787. Matrix.prototype.addToRef = function (other, result) {
  2788. for (var index = 0; index < 16; index++) {
  2789. result.m[index] = this.m[index] + other.m[index];
  2790. }
  2791. result._markAsUpdated();
  2792. return this;
  2793. };
  2794. /**
  2795. * Adds in place the passed matrix to the current Matrix.
  2796. * Returns the updated Matrix.
  2797. */
  2798. Matrix.prototype.addToSelf = function (other) {
  2799. for (var index = 0; index < 16; index++) {
  2800. this.m[index] += other.m[index];
  2801. }
  2802. this._markAsUpdated();
  2803. return this;
  2804. };
  2805. /**
  2806. * Sets the passed matrix with the current inverted Matrix.
  2807. * Returns the unmodified current Matrix.
  2808. */
  2809. Matrix.prototype.invertToRef = function (other) {
  2810. var l1 = this.m[0];
  2811. var l2 = this.m[1];
  2812. var l3 = this.m[2];
  2813. var l4 = this.m[3];
  2814. var l5 = this.m[4];
  2815. var l6 = this.m[5];
  2816. var l7 = this.m[6];
  2817. var l8 = this.m[7];
  2818. var l9 = this.m[8];
  2819. var l10 = this.m[9];
  2820. var l11 = this.m[10];
  2821. var l12 = this.m[11];
  2822. var l13 = this.m[12];
  2823. var l14 = this.m[13];
  2824. var l15 = this.m[14];
  2825. var l16 = this.m[15];
  2826. var l17 = (l11 * l16) - (l12 * l15);
  2827. var l18 = (l10 * l16) - (l12 * l14);
  2828. var l19 = (l10 * l15) - (l11 * l14);
  2829. var l20 = (l9 * l16) - (l12 * l13);
  2830. var l21 = (l9 * l15) - (l11 * l13);
  2831. var l22 = (l9 * l14) - (l10 * l13);
  2832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2837. var l28 = (l7 * l16) - (l8 * l15);
  2838. var l29 = (l6 * l16) - (l8 * l14);
  2839. var l30 = (l6 * l15) - (l7 * l14);
  2840. var l31 = (l5 * l16) - (l8 * l13);
  2841. var l32 = (l5 * l15) - (l7 * l13);
  2842. var l33 = (l5 * l14) - (l6 * l13);
  2843. var l34 = (l7 * l12) - (l8 * l11);
  2844. var l35 = (l6 * l12) - (l8 * l10);
  2845. var l36 = (l6 * l11) - (l7 * l10);
  2846. var l37 = (l5 * l12) - (l8 * l9);
  2847. var l38 = (l5 * l11) - (l7 * l9);
  2848. var l39 = (l5 * l10) - (l6 * l9);
  2849. other.m[0] = l23 * l27;
  2850. other.m[4] = l24 * l27;
  2851. other.m[8] = l25 * l27;
  2852. other.m[12] = l26 * l27;
  2853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2865. other._markAsUpdated();
  2866. return this;
  2867. };
  2868. /**
  2869. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2870. * Returns the updated Matrix.
  2871. */
  2872. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2873. this.m[12] = x;
  2874. this.m[13] = y;
  2875. this.m[14] = z;
  2876. this._markAsUpdated();
  2877. return this;
  2878. };
  2879. /**
  2880. * Inserts the translation vector in the current Matrix.
  2881. * Returns the updated Matrix.
  2882. */
  2883. Matrix.prototype.setTranslation = function (vector3) {
  2884. this.m[12] = vector3.x;
  2885. this.m[13] = vector3.y;
  2886. this.m[14] = vector3.z;
  2887. this._markAsUpdated();
  2888. return this;
  2889. };
  2890. /**
  2891. * Returns a new Vector3 as the extracted translation from the Matrix.
  2892. */
  2893. Matrix.prototype.getTranslation = function () {
  2894. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2895. };
  2896. /**
  2897. * Fill a Vector3 with the extracted translation from the Matrix.
  2898. */
  2899. Matrix.prototype.getTranslationToRef = function (result) {
  2900. result.x = this.m[12];
  2901. result.y = this.m[13];
  2902. result.z = this.m[14];
  2903. return this;
  2904. };
  2905. /**
  2906. * Remove rotation and scaling part from the Matrix.
  2907. * Returns the updated Matrix.
  2908. */
  2909. Matrix.prototype.removeRotationAndScaling = function () {
  2910. this.setRowFromFloats(0, 1, 0, 0, 0);
  2911. this.setRowFromFloats(1, 0, 1, 0, 0);
  2912. this.setRowFromFloats(2, 0, 0, 1, 0);
  2913. return this;
  2914. };
  2915. /**
  2916. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2917. */
  2918. Matrix.prototype.multiply = function (other) {
  2919. var result = new Matrix();
  2920. this.multiplyToRef(other, result);
  2921. return result;
  2922. };
  2923. /**
  2924. * Updates the current Matrix from the passed one values.
  2925. * Returns the updated Matrix.
  2926. */
  2927. Matrix.prototype.copyFrom = function (other) {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = other.m[index];
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Populates the passed array from the starting index with the Matrix values.
  2936. * Returns the Matrix.
  2937. */
  2938. Matrix.prototype.copyToArray = function (array, offset) {
  2939. if (offset === void 0) { offset = 0; }
  2940. for (var index = 0; index < 16; index++) {
  2941. array[offset + index] = this.m[index];
  2942. }
  2943. return this;
  2944. };
  2945. /**
  2946. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2947. */
  2948. Matrix.prototype.multiplyToRef = function (other, result) {
  2949. this.multiplyToArray(other, result.m, 0);
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2957. var tm0 = this.m[0];
  2958. var tm1 = this.m[1];
  2959. var tm2 = this.m[2];
  2960. var tm3 = this.m[3];
  2961. var tm4 = this.m[4];
  2962. var tm5 = this.m[5];
  2963. var tm6 = this.m[6];
  2964. var tm7 = this.m[7];
  2965. var tm8 = this.m[8];
  2966. var tm9 = this.m[9];
  2967. var tm10 = this.m[10];
  2968. var tm11 = this.m[11];
  2969. var tm12 = this.m[12];
  2970. var tm13 = this.m[13];
  2971. var tm14 = this.m[14];
  2972. var tm15 = this.m[15];
  2973. var om0 = other.m[0];
  2974. var om1 = other.m[1];
  2975. var om2 = other.m[2];
  2976. var om3 = other.m[3];
  2977. var om4 = other.m[4];
  2978. var om5 = other.m[5];
  2979. var om6 = other.m[6];
  2980. var om7 = other.m[7];
  2981. var om8 = other.m[8];
  2982. var om9 = other.m[9];
  2983. var om10 = other.m[10];
  2984. var om11 = other.m[11];
  2985. var om12 = other.m[12];
  2986. var om13 = other.m[13];
  2987. var om14 = other.m[14];
  2988. var om15 = other.m[15];
  2989. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2990. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2991. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2992. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2993. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2994. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2995. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2996. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2997. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2998. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2999. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3000. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3001. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3002. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3003. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3004. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3005. return this;
  3006. };
  3007. /**
  3008. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3009. */
  3010. Matrix.prototype.equals = function (value) {
  3011. return value &&
  3012. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3013. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3014. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3015. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3016. };
  3017. /**
  3018. * Returns a new Matrix from the current Matrix.
  3019. */
  3020. Matrix.prototype.clone = function () {
  3021. 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]);
  3022. };
  3023. /**
  3024. * Returns the string "Matrix"
  3025. */
  3026. Matrix.prototype.getClassName = function () {
  3027. return "Matrix";
  3028. };
  3029. /**
  3030. * Returns the Matrix hash code.
  3031. */
  3032. Matrix.prototype.getHashCode = function () {
  3033. var hash = this.m[0] || 0;
  3034. for (var i = 1; i < 16; i++) {
  3035. hash = (hash * 397) ^ (this.m[i] || 0);
  3036. }
  3037. return hash;
  3038. };
  3039. /**
  3040. * Decomposes the current Matrix into :
  3041. * - a scale vector3 passed as a reference to update,
  3042. * - a rotation quaternion passed as a reference to update,
  3043. * - a translation vector3 passed as a reference to update.
  3044. * Returns the boolean `true`.
  3045. */
  3046. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3047. translation.x = this.m[12];
  3048. translation.y = this.m[13];
  3049. translation.z = this.m[14];
  3050. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3051. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3052. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3053. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3054. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3055. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3056. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3057. rotation.x = 0;
  3058. rotation.y = 0;
  3059. rotation.z = 0;
  3060. rotation.w = 1;
  3061. return false;
  3062. }
  3063. 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]);
  3064. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3065. return true;
  3066. };
  3067. /**
  3068. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3069. */
  3070. Matrix.prototype.getRotationMatrix = function () {
  3071. var result = Matrix.Identity();
  3072. this.getRotationMatrixToRef(result);
  3073. return result;
  3074. };
  3075. /**
  3076. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3077. * Returns the current Matrix.
  3078. */
  3079. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3080. var m = this.m;
  3081. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3082. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3083. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3084. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3085. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3086. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3087. 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);
  3088. return this;
  3089. };
  3090. // Statics
  3091. /**
  3092. * Returns a new Matrix set from the starting index of the passed array.
  3093. */
  3094. Matrix.FromArray = function (array, offset) {
  3095. var result = new Matrix();
  3096. if (!offset) {
  3097. offset = 0;
  3098. }
  3099. Matrix.FromArrayToRef(array, offset, result);
  3100. return result;
  3101. };
  3102. /**
  3103. * Sets the passed "result" matrix from the starting index of the passed array.
  3104. */
  3105. Matrix.FromArrayToRef = function (array, offset, result) {
  3106. for (var index = 0; index < 16; index++) {
  3107. result.m[index] = array[index + offset];
  3108. }
  3109. result._markAsUpdated();
  3110. };
  3111. /**
  3112. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3113. */
  3114. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3115. for (var index = 0; index < 16; index++) {
  3116. result.m[index] = array[index + offset] * scale;
  3117. }
  3118. result._markAsUpdated();
  3119. };
  3120. /**
  3121. * Sets the passed matrix "result" with the 16 passed floats.
  3122. */
  3123. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3124. result.m[0] = initialM11;
  3125. result.m[1] = initialM12;
  3126. result.m[2] = initialM13;
  3127. result.m[3] = initialM14;
  3128. result.m[4] = initialM21;
  3129. result.m[5] = initialM22;
  3130. result.m[6] = initialM23;
  3131. result.m[7] = initialM24;
  3132. result.m[8] = initialM31;
  3133. result.m[9] = initialM32;
  3134. result.m[10] = initialM33;
  3135. result.m[11] = initialM34;
  3136. result.m[12] = initialM41;
  3137. result.m[13] = initialM42;
  3138. result.m[14] = initialM43;
  3139. result.m[15] = initialM44;
  3140. result._markAsUpdated();
  3141. };
  3142. /**
  3143. * Returns the index-th row of the current matrix as a new Vector4.
  3144. */
  3145. Matrix.prototype.getRow = function (index) {
  3146. if (index < 0 || index > 3) {
  3147. return null;
  3148. }
  3149. var i = index * 4;
  3150. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3151. };
  3152. /**
  3153. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3154. * Returns the updated Matrix.
  3155. */
  3156. Matrix.prototype.setRow = function (index, row) {
  3157. if (index < 0 || index > 3) {
  3158. return this;
  3159. }
  3160. var i = index * 4;
  3161. this.m[i + 0] = row.x;
  3162. this.m[i + 1] = row.y;
  3163. this.m[i + 2] = row.z;
  3164. this.m[i + 3] = row.w;
  3165. this._markAsUpdated();
  3166. return this;
  3167. };
  3168. /**
  3169. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3170. * Returns the updated Matrix.
  3171. */
  3172. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3173. if (index < 0 || index > 3) {
  3174. return this;
  3175. }
  3176. var i = index * 4;
  3177. this.m[i + 0] = x;
  3178. this.m[i + 1] = y;
  3179. this.m[i + 2] = z;
  3180. this.m[i + 3] = w;
  3181. this._markAsUpdated();
  3182. return this;
  3183. };
  3184. /**
  3185. * Returns a new Matrix set from the 16 passed floats.
  3186. */
  3187. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3188. var result = new Matrix();
  3189. result.m[0] = initialM11;
  3190. result.m[1] = initialM12;
  3191. result.m[2] = initialM13;
  3192. result.m[3] = initialM14;
  3193. result.m[4] = initialM21;
  3194. result.m[5] = initialM22;
  3195. result.m[6] = initialM23;
  3196. result.m[7] = initialM24;
  3197. result.m[8] = initialM31;
  3198. result.m[9] = initialM32;
  3199. result.m[10] = initialM33;
  3200. result.m[11] = initialM34;
  3201. result.m[12] = initialM41;
  3202. result.m[13] = initialM42;
  3203. result.m[14] = initialM43;
  3204. result.m[15] = initialM44;
  3205. return result;
  3206. };
  3207. /**
  3208. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3209. */
  3210. Matrix.Compose = function (scale, rotation, translation) {
  3211. var result = Matrix.Identity();
  3212. Matrix.ComposeToRef(scale, rotation, translation, result);
  3213. return result;
  3214. };
  3215. /**
  3216. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3219. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3220. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3221. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3222. result.setTranslation(translation);
  3223. };
  3224. /**
  3225. * Returns a new indentity Matrix.
  3226. */
  3227. Matrix.Identity = function () {
  3228. 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);
  3229. };
  3230. /**
  3231. * Sets the passed "result" as an identity matrix.
  3232. */
  3233. Matrix.IdentityToRef = function (result) {
  3234. 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);
  3235. };
  3236. /**
  3237. * Returns a new zero Matrix.
  3238. */
  3239. Matrix.Zero = function () {
  3240. 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);
  3241. };
  3242. /**
  3243. * Returns a new rotation matrix for "angle" radians around the X axis.
  3244. */
  3245. Matrix.RotationX = function (angle) {
  3246. var result = new Matrix();
  3247. Matrix.RotationXToRef(angle, result);
  3248. return result;
  3249. };
  3250. /**
  3251. * Returns a new Matrix as the passed inverted one.
  3252. */
  3253. Matrix.Invert = function (source) {
  3254. var result = new Matrix();
  3255. source.invertToRef(result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3260. */
  3261. Matrix.RotationXToRef = function (angle, result) {
  3262. var s = Math.sin(angle);
  3263. var c = Math.cos(angle);
  3264. result.m[0] = 1.0;
  3265. result.m[15] = 1.0;
  3266. result.m[5] = c;
  3267. result.m[10] = c;
  3268. result.m[9] = -s;
  3269. result.m[6] = s;
  3270. result.m[1] = 0.0;
  3271. result.m[2] = 0.0;
  3272. result.m[3] = 0.0;
  3273. result.m[4] = 0.0;
  3274. result.m[7] = 0.0;
  3275. result.m[8] = 0.0;
  3276. result.m[11] = 0.0;
  3277. result.m[12] = 0.0;
  3278. result.m[13] = 0.0;
  3279. result.m[14] = 0.0;
  3280. result._markAsUpdated();
  3281. };
  3282. /**
  3283. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3284. */
  3285. Matrix.RotationY = function (angle) {
  3286. var result = new Matrix();
  3287. Matrix.RotationYToRef(angle, result);
  3288. return result;
  3289. };
  3290. /**
  3291. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationYToRef = function (angle, result) {
  3294. var s = Math.sin(angle);
  3295. var c = Math.cos(angle);
  3296. result.m[5] = 1.0;
  3297. result.m[15] = 1.0;
  3298. result.m[0] = c;
  3299. result.m[2] = -s;
  3300. result.m[8] = s;
  3301. result.m[10] = c;
  3302. result.m[1] = 0.0;
  3303. result.m[3] = 0.0;
  3304. result.m[4] = 0.0;
  3305. result.m[6] = 0.0;
  3306. result.m[7] = 0.0;
  3307. result.m[9] = 0.0;
  3308. result.m[11] = 0.0;
  3309. result.m[12] = 0.0;
  3310. result.m[13] = 0.0;
  3311. result.m[14] = 0.0;
  3312. result._markAsUpdated();
  3313. };
  3314. /**
  3315. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3316. */
  3317. Matrix.RotationZ = function (angle) {
  3318. var result = new Matrix();
  3319. Matrix.RotationZToRef(angle, result);
  3320. return result;
  3321. };
  3322. /**
  3323. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZToRef = function (angle, result) {
  3326. var s = Math.sin(angle);
  3327. var c = Math.cos(angle);
  3328. result.m[10] = 1.0;
  3329. result.m[15] = 1.0;
  3330. result.m[0] = c;
  3331. result.m[1] = s;
  3332. result.m[4] = -s;
  3333. result.m[5] = c;
  3334. result.m[2] = 0.0;
  3335. result.m[3] = 0.0;
  3336. result.m[6] = 0.0;
  3337. result.m[7] = 0.0;
  3338. result.m[8] = 0.0;
  3339. result.m[9] = 0.0;
  3340. result.m[11] = 0.0;
  3341. result.m[12] = 0.0;
  3342. result.m[13] = 0.0;
  3343. result.m[14] = 0.0;
  3344. result._markAsUpdated();
  3345. };
  3346. /**
  3347. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3348. */
  3349. Matrix.RotationAxis = function (axis, angle) {
  3350. var result = Matrix.Zero();
  3351. Matrix.RotationAxisToRef(axis, angle, result);
  3352. return result;
  3353. };
  3354. /**
  3355. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3358. var s = Math.sin(-angle);
  3359. var c = Math.cos(-angle);
  3360. var c1 = 1 - c;
  3361. axis.normalize();
  3362. result.m[0] = (axis.x * axis.x) * c1 + c;
  3363. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3364. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3365. result.m[3] = 0.0;
  3366. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3367. result.m[5] = (axis.y * axis.y) * c1 + c;
  3368. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3369. result.m[7] = 0.0;
  3370. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3371. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3372. result.m[10] = (axis.z * axis.z) * c1 + c;
  3373. result.m[11] = 0.0;
  3374. result.m[15] = 1.0;
  3375. result._markAsUpdated();
  3376. };
  3377. /**
  3378. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3379. */
  3380. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3381. var result = new Matrix();
  3382. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3383. return result;
  3384. };
  3385. /**
  3386. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3389. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3390. this._tempQuaternion.toRotationMatrix(result);
  3391. };
  3392. /**
  3393. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3394. */
  3395. Matrix.Scaling = function (x, y, z) {
  3396. var result = Matrix.Zero();
  3397. Matrix.ScalingToRef(x, y, z, result);
  3398. return result;
  3399. };
  3400. /**
  3401. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.ScalingToRef = function (x, y, z, result) {
  3404. result.m[0] = x;
  3405. result.m[1] = 0.0;
  3406. result.m[2] = 0.0;
  3407. result.m[3] = 0.0;
  3408. result.m[4] = 0.0;
  3409. result.m[5] = y;
  3410. result.m[6] = 0.0;
  3411. result.m[7] = 0.0;
  3412. result.m[8] = 0.0;
  3413. result.m[9] = 0.0;
  3414. result.m[10] = z;
  3415. result.m[11] = 0.0;
  3416. result.m[12] = 0.0;
  3417. result.m[13] = 0.0;
  3418. result.m[14] = 0.0;
  3419. result.m[15] = 1.0;
  3420. result._markAsUpdated();
  3421. };
  3422. /**
  3423. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3424. */
  3425. Matrix.Translation = function (x, y, z) {
  3426. var result = Matrix.Identity();
  3427. Matrix.TranslationToRef(x, y, z, result);
  3428. return result;
  3429. };
  3430. /**
  3431. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.TranslationToRef = function (x, y, z, result) {
  3434. 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);
  3435. };
  3436. /**
  3437. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3438. */
  3439. Matrix.Lerp = function (startValue, endValue, gradient) {
  3440. var result = Matrix.Zero();
  3441. for (var index = 0; index < 16; index++) {
  3442. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3443. }
  3444. result._markAsUpdated();
  3445. return result;
  3446. };
  3447. /**
  3448. * Returns a new Matrix whose values are computed by :
  3449. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3450. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3451. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3452. */
  3453. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3454. var startScale = new Vector3(0, 0, 0);
  3455. var startRotation = new Quaternion();
  3456. var startTranslation = new Vector3(0, 0, 0);
  3457. startValue.decompose(startScale, startRotation, startTranslation);
  3458. var endScale = new Vector3(0, 0, 0);
  3459. var endRotation = new Quaternion();
  3460. var endTranslation = new Vector3(0, 0, 0);
  3461. endValue.decompose(endScale, endRotation, endTranslation);
  3462. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3463. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3464. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3465. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3466. };
  3467. /**
  3468. * 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".
  3469. * This methods works for a Left-Handed system.
  3470. */
  3471. Matrix.LookAtLH = function (eye, target, up) {
  3472. var result = Matrix.Zero();
  3473. Matrix.LookAtLHToRef(eye, target, up, result);
  3474. return result;
  3475. };
  3476. /**
  3477. * 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".
  3478. * This methods works for a Left-Handed system.
  3479. */
  3480. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3481. // Z axis
  3482. target.subtractToRef(eye, this._zAxis);
  3483. this._zAxis.normalize();
  3484. // X axis
  3485. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3486. if (this._xAxis.lengthSquared() === 0) {
  3487. this._xAxis.x = 1.0;
  3488. }
  3489. else {
  3490. this._xAxis.normalize();
  3491. }
  3492. // Y axis
  3493. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3494. this._yAxis.normalize();
  3495. // Eye angles
  3496. var ex = -Vector3.Dot(this._xAxis, eye);
  3497. var ey = -Vector3.Dot(this._yAxis, eye);
  3498. var ez = -Vector3.Dot(this._zAxis, eye);
  3499. 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);
  3500. };
  3501. /**
  3502. * 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".
  3503. * This methods works for a Right-Handed system.
  3504. */
  3505. Matrix.LookAtRH = function (eye, target, up) {
  3506. var result = Matrix.Zero();
  3507. Matrix.LookAtRHToRef(eye, target, up, result);
  3508. return result;
  3509. };
  3510. /**
  3511. * 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".
  3512. * This methods works for a Left-Handed system.
  3513. */
  3514. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3515. // Z axis
  3516. eye.subtractToRef(target, this._zAxis);
  3517. this._zAxis.normalize();
  3518. // X axis
  3519. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3520. if (this._xAxis.lengthSquared() === 0) {
  3521. this._xAxis.x = 1.0;
  3522. }
  3523. else {
  3524. this._xAxis.normalize();
  3525. }
  3526. // Y axis
  3527. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3528. this._yAxis.normalize();
  3529. // Eye angles
  3530. var ex = -Vector3.Dot(this._xAxis, eye);
  3531. var ey = -Vector3.Dot(this._yAxis, eye);
  3532. var ez = -Vector3.Dot(this._zAxis, eye);
  3533. 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);
  3534. };
  3535. /**
  3536. * 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.
  3537. */
  3538. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3539. var matrix = Matrix.Zero();
  3540. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3541. return matrix;
  3542. };
  3543. /**
  3544. * 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.
  3545. */
  3546. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3547. var n = znear;
  3548. var f = zfar;
  3549. var a = 2.0 / width;
  3550. var b = 2.0 / height;
  3551. var c = 2.0 / (f - n);
  3552. var d = -(f + n) / (f - n);
  3553. 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);
  3554. };
  3555. /**
  3556. * 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.
  3557. */
  3558. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3559. var matrix = Matrix.Zero();
  3560. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3561. return matrix;
  3562. };
  3563. /**
  3564. * 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.
  3565. */
  3566. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3567. var n = znear;
  3568. var f = zfar;
  3569. var a = 2.0 / (right - left);
  3570. var b = 2.0 / (top - bottom);
  3571. var c = 2.0 / (f - n);
  3572. var d = -(f + n) / (f - n);
  3573. var i0 = (left + right) / (left - right);
  3574. var i1 = (top + bottom) / (bottom - top);
  3575. 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);
  3576. };
  3577. /**
  3578. * 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.
  3579. */
  3580. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3581. var matrix = Matrix.Zero();
  3582. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3583. return matrix;
  3584. };
  3585. /**
  3586. * 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.
  3587. */
  3588. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3589. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3590. result.m[10] *= -1.0;
  3591. };
  3592. /**
  3593. * 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.
  3594. */
  3595. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3596. var matrix = Matrix.Zero();
  3597. var n = znear;
  3598. var f = zfar;
  3599. var a = 2.0 * n / width;
  3600. var b = 2.0 * n / height;
  3601. var c = (f + n) / (f - n);
  3602. var d = -2.0 * f * n / (f - n);
  3603. 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);
  3604. return matrix;
  3605. };
  3606. /**
  3607. * 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.
  3608. */
  3609. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3610. var matrix = Matrix.Zero();
  3611. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * 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.
  3616. */
  3617. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3618. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3619. var n = znear;
  3620. var f = zfar;
  3621. var t = 1.0 / (Math.tan(fov * 0.5));
  3622. var a = isVerticalFovFixed ? (t / aspect) : t;
  3623. var b = isVerticalFovFixed ? t : (t * aspect);
  3624. var c = (f + n) / (f - n);
  3625. var d = -2.0 * f * n / (f - n);
  3626. 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);
  3627. };
  3628. /**
  3629. * 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.
  3630. */
  3631. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3632. var matrix = Matrix.Zero();
  3633. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3634. return matrix;
  3635. };
  3636. /**
  3637. * 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.
  3638. */
  3639. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3640. //alternatively this could be expressed as:
  3641. // m = PerspectiveFovLHToRef
  3642. // m[10] *= -1.0;
  3643. // m[11] *= -1.0;
  3644. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3645. var n = znear;
  3646. var f = zfar;
  3647. var t = 1.0 / (Math.tan(fov * 0.5));
  3648. var a = isVerticalFovFixed ? (t / aspect) : t;
  3649. var b = isVerticalFovFixed ? t : (t * aspect);
  3650. var c = -(f + n) / (f - n);
  3651. var d = -2 * f * n / (f - n);
  3652. 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);
  3653. };
  3654. /**
  3655. * 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.
  3656. */
  3657. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3658. if (rightHanded === void 0) { rightHanded = false; }
  3659. var rightHandedFactor = rightHanded ? -1 : 1;
  3660. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3661. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3662. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3663. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3664. var xScale = 2.0 / (leftTan + rightTan);
  3665. var yScale = 2.0 / (upTan + downTan);
  3666. result.m[0] = xScale;
  3667. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3668. result.m[5] = yScale;
  3669. result.m[6] = result.m[7] = 0.0;
  3670. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3671. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3672. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3673. result.m[10] = -zfar / (znear - zfar);
  3674. result.m[11] = 1.0 * rightHandedFactor;
  3675. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3676. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3677. // result.m[14] = (znear * zfar) / (znear - zfar);
  3678. result._markAsUpdated();
  3679. };
  3680. /**
  3681. * Returns the final transformation matrix : world * view * projection * viewport
  3682. */
  3683. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3684. var cw = viewport.width;
  3685. var ch = viewport.height;
  3686. var cx = viewport.x;
  3687. var cy = viewport.y;
  3688. 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);
  3689. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3690. };
  3691. /**
  3692. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3693. */
  3694. Matrix.GetAsMatrix2x2 = function (matrix) {
  3695. return new Float32Array([
  3696. matrix.m[0], matrix.m[1],
  3697. matrix.m[4], matrix.m[5]
  3698. ]);
  3699. };
  3700. /**
  3701. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3702. */
  3703. Matrix.GetAsMatrix3x3 = function (matrix) {
  3704. return new Float32Array([
  3705. matrix.m[0], matrix.m[1], matrix.m[2],
  3706. matrix.m[4], matrix.m[5], matrix.m[6],
  3707. matrix.m[8], matrix.m[9], matrix.m[10]
  3708. ]);
  3709. };
  3710. /**
  3711. * Compute the transpose of the passed Matrix.
  3712. * Returns a new Matrix.
  3713. */
  3714. Matrix.Transpose = function (matrix) {
  3715. var result = new Matrix();
  3716. result.m[0] = matrix.m[0];
  3717. result.m[1] = matrix.m[4];
  3718. result.m[2] = matrix.m[8];
  3719. result.m[3] = matrix.m[12];
  3720. result.m[4] = matrix.m[1];
  3721. result.m[5] = matrix.m[5];
  3722. result.m[6] = matrix.m[9];
  3723. result.m[7] = matrix.m[13];
  3724. result.m[8] = matrix.m[2];
  3725. result.m[9] = matrix.m[6];
  3726. result.m[10] = matrix.m[10];
  3727. result.m[11] = matrix.m[14];
  3728. result.m[12] = matrix.m[3];
  3729. result.m[13] = matrix.m[7];
  3730. result.m[14] = matrix.m[11];
  3731. result.m[15] = matrix.m[15];
  3732. return result;
  3733. };
  3734. /**
  3735. * Returns a new Matrix as the reflection matrix across the passed plane.
  3736. */
  3737. Matrix.Reflection = function (plane) {
  3738. var matrix = new Matrix();
  3739. Matrix.ReflectionToRef(plane, matrix);
  3740. return matrix;
  3741. };
  3742. /**
  3743. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.ReflectionToRef = function (plane, result) {
  3746. plane.normalize();
  3747. var x = plane.normal.x;
  3748. var y = plane.normal.y;
  3749. var z = plane.normal.z;
  3750. var temp = -2 * x;
  3751. var temp2 = -2 * y;
  3752. var temp3 = -2 * z;
  3753. result.m[0] = (temp * x) + 1;
  3754. result.m[1] = temp2 * x;
  3755. result.m[2] = temp3 * x;
  3756. result.m[3] = 0.0;
  3757. result.m[4] = temp * y;
  3758. result.m[5] = (temp2 * y) + 1;
  3759. result.m[6] = temp3 * y;
  3760. result.m[7] = 0.0;
  3761. result.m[8] = temp * z;
  3762. result.m[9] = temp2 * z;
  3763. result.m[10] = (temp3 * z) + 1;
  3764. result.m[11] = 0.0;
  3765. result.m[12] = temp * plane.d;
  3766. result.m[13] = temp2 * plane.d;
  3767. result.m[14] = temp3 * plane.d;
  3768. result.m[15] = 1.0;
  3769. result._markAsUpdated();
  3770. };
  3771. /**
  3772. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3773. */
  3774. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3775. result.m[0] = xaxis.x;
  3776. result.m[1] = xaxis.y;
  3777. result.m[2] = xaxis.z;
  3778. result.m[3] = 0.0;
  3779. result.m[4] = yaxis.x;
  3780. result.m[5] = yaxis.y;
  3781. result.m[6] = yaxis.z;
  3782. result.m[7] = 0.0;
  3783. result.m[8] = zaxis.x;
  3784. result.m[9] = zaxis.y;
  3785. result.m[10] = zaxis.z;
  3786. result.m[11] = 0.0;
  3787. result.m[12] = 0.0;
  3788. result.m[13] = 0.0;
  3789. result.m[14] = 0.0;
  3790. result.m[15] = 1.0;
  3791. result._markAsUpdated();
  3792. };
  3793. /**
  3794. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3795. */
  3796. Matrix.FromQuaternionToRef = function (quat, result) {
  3797. var xx = quat.x * quat.x;
  3798. var yy = quat.y * quat.y;
  3799. var zz = quat.z * quat.z;
  3800. var xy = quat.x * quat.y;
  3801. var zw = quat.z * quat.w;
  3802. var zx = quat.z * quat.x;
  3803. var yw = quat.y * quat.w;
  3804. var yz = quat.y * quat.z;
  3805. var xw = quat.x * quat.w;
  3806. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3807. result.m[1] = 2.0 * (xy + zw);
  3808. result.m[2] = 2.0 * (zx - yw);
  3809. result.m[3] = 0.0;
  3810. result.m[4] = 2.0 * (xy - zw);
  3811. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3812. result.m[6] = 2.0 * (yz + xw);
  3813. result.m[7] = 0.0;
  3814. result.m[8] = 2.0 * (zx + yw);
  3815. result.m[9] = 2.0 * (yz - xw);
  3816. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3817. result.m[11] = 0.0;
  3818. result.m[12] = 0.0;
  3819. result.m[13] = 0.0;
  3820. result.m[14] = 0.0;
  3821. result.m[15] = 1.0;
  3822. result._markAsUpdated();
  3823. };
  3824. return Matrix;
  3825. }());
  3826. Matrix._tempQuaternion = new Quaternion();
  3827. Matrix._xAxis = Vector3.Zero();
  3828. Matrix._yAxis = Vector3.Zero();
  3829. Matrix._zAxis = Vector3.Zero();
  3830. Matrix._updateFlagSeed = 0;
  3831. BABYLON.Matrix = Matrix;
  3832. var Plane = (function () {
  3833. /**
  3834. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3835. */
  3836. function Plane(a, b, c, d) {
  3837. this.normal = new Vector3(a, b, c);
  3838. this.d = d;
  3839. }
  3840. /**
  3841. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3842. */
  3843. Plane.prototype.asArray = function () {
  3844. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3845. };
  3846. // Methods
  3847. /**
  3848. * Returns a new plane copied from the current Plane.
  3849. */
  3850. Plane.prototype.clone = function () {
  3851. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3852. };
  3853. /**
  3854. * Returns the string "Plane".
  3855. */
  3856. Plane.prototype.getClassName = function () {
  3857. return "Plane";
  3858. };
  3859. /**
  3860. * Returns the Plane hash code.
  3861. */
  3862. Plane.prototype.getHashCode = function () {
  3863. var hash = this.normal.getHashCode();
  3864. hash = (hash * 397) ^ (this.d || 0);
  3865. return hash;
  3866. };
  3867. /**
  3868. * Normalize the current Plane in place.
  3869. * Returns the updated Plane.
  3870. */
  3871. Plane.prototype.normalize = function () {
  3872. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3873. var magnitude = 0.0;
  3874. if (norm !== 0) {
  3875. magnitude = 1.0 / norm;
  3876. }
  3877. this.normal.x *= magnitude;
  3878. this.normal.y *= magnitude;
  3879. this.normal.z *= magnitude;
  3880. this.d *= magnitude;
  3881. return this;
  3882. };
  3883. /**
  3884. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3885. */
  3886. Plane.prototype.transform = function (transformation) {
  3887. var transposedMatrix = Matrix.Transpose(transformation);
  3888. var x = this.normal.x;
  3889. var y = this.normal.y;
  3890. var z = this.normal.z;
  3891. var d = this.d;
  3892. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3893. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3894. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3895. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3896. return new Plane(normalX, normalY, normalZ, finalD);
  3897. };
  3898. /**
  3899. * Returns the dot product (float) of the point coordinates and the plane normal.
  3900. */
  3901. Plane.prototype.dotCoordinate = function (point) {
  3902. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3903. };
  3904. /**
  3905. * Updates the current Plane from the plane defined by the three passed points.
  3906. * Returns the updated Plane.
  3907. */
  3908. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3909. var x1 = point2.x - point1.x;
  3910. var y1 = point2.y - point1.y;
  3911. var z1 = point2.z - point1.z;
  3912. var x2 = point3.x - point1.x;
  3913. var y2 = point3.y - point1.y;
  3914. var z2 = point3.z - point1.z;
  3915. var yz = (y1 * z2) - (z1 * y2);
  3916. var xz = (z1 * x2) - (x1 * z2);
  3917. var xy = (x1 * y2) - (y1 * x2);
  3918. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3919. var invPyth;
  3920. if (pyth !== 0) {
  3921. invPyth = 1.0 / pyth;
  3922. }
  3923. else {
  3924. invPyth = 0.0;
  3925. }
  3926. this.normal.x = yz * invPyth;
  3927. this.normal.y = xz * invPyth;
  3928. this.normal.z = xy * invPyth;
  3929. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3930. return this;
  3931. };
  3932. /**
  3933. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3934. */
  3935. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3936. var dot = Vector3.Dot(this.normal, direction);
  3937. return (dot <= epsilon);
  3938. };
  3939. /**
  3940. * Returns the signed distance (float) from the passed point to the Plane.
  3941. */
  3942. Plane.prototype.signedDistanceTo = function (point) {
  3943. return Vector3.Dot(point, this.normal) + this.d;
  3944. };
  3945. // Statics
  3946. /**
  3947. * Returns a new Plane from the passed array.
  3948. */
  3949. Plane.FromArray = function (array) {
  3950. return new Plane(array[0], array[1], array[2], array[3]);
  3951. };
  3952. /**
  3953. * Returns a new Plane defined by the three passed points.
  3954. */
  3955. Plane.FromPoints = function (point1, point2, point3) {
  3956. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3957. result.copyFromPoints(point1, point2, point3);
  3958. return result;
  3959. };
  3960. /**
  3961. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3962. * Note : the vector "normal" is updated because normalized.
  3963. */
  3964. Plane.FromPositionAndNormal = function (origin, normal) {
  3965. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3966. normal.normalize();
  3967. result.normal = normal;
  3968. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3969. return result;
  3970. };
  3971. /**
  3972. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3973. */
  3974. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3975. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3976. return Vector3.Dot(point, normal) + d;
  3977. };
  3978. return Plane;
  3979. }());
  3980. BABYLON.Plane = Plane;
  3981. var Viewport = (function () {
  3982. /**
  3983. * Creates a Viewport object located at (x, y) and sized (width, height).
  3984. */
  3985. function Viewport(x, y, width, height) {
  3986. this.x = x;
  3987. this.y = y;
  3988. this.width = width;
  3989. this.height = height;
  3990. }
  3991. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3992. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3993. };
  3994. /**
  3995. * Returns a new Viewport copied from the current one.
  3996. */
  3997. Viewport.prototype.clone = function () {
  3998. return new Viewport(this.x, this.y, this.width, this.height);
  3999. };
  4000. return Viewport;
  4001. }());
  4002. BABYLON.Viewport = Viewport;
  4003. var Frustum = (function () {
  4004. function Frustum() {
  4005. }
  4006. /**
  4007. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4008. */
  4009. Frustum.GetPlanes = function (transform) {
  4010. var frustumPlanes = [];
  4011. for (var index = 0; index < 6; index++) {
  4012. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4013. }
  4014. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4015. return frustumPlanes;
  4016. };
  4017. /**
  4018. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4019. */
  4020. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4021. // Near
  4022. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4023. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4024. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4025. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4026. frustumPlanes[0].normalize();
  4027. // Far
  4028. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4029. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4030. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4031. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4032. frustumPlanes[1].normalize();
  4033. // Left
  4034. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4035. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4036. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4037. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4038. frustumPlanes[2].normalize();
  4039. // Right
  4040. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4041. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4042. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4043. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4044. frustumPlanes[3].normalize();
  4045. // Top
  4046. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4047. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4048. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4049. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4050. frustumPlanes[4].normalize();
  4051. // Bottom
  4052. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4053. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4054. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4055. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4056. frustumPlanes[5].normalize();
  4057. };
  4058. return Frustum;
  4059. }());
  4060. BABYLON.Frustum = Frustum;
  4061. var Space;
  4062. (function (Space) {
  4063. Space[Space["LOCAL"] = 0] = "LOCAL";
  4064. Space[Space["WORLD"] = 1] = "WORLD";
  4065. Space[Space["BONE"] = 2] = "BONE";
  4066. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4067. var Axis = (function () {
  4068. function Axis() {
  4069. }
  4070. return Axis;
  4071. }());
  4072. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4073. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4074. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4075. BABYLON.Axis = Axis;
  4076. ;
  4077. var BezierCurve = (function () {
  4078. function BezierCurve() {
  4079. }
  4080. /**
  4081. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4082. */
  4083. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4084. // Extract X (which is equal to time here)
  4085. var f0 = 1 - 3 * x2 + 3 * x1;
  4086. var f1 = 3 * x2 - 6 * x1;
  4087. var f2 = 3 * x1;
  4088. var refinedT = t;
  4089. for (var i = 0; i < 5; i++) {
  4090. var refinedT2 = refinedT * refinedT;
  4091. var refinedT3 = refinedT2 * refinedT;
  4092. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4093. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4094. refinedT -= (x - t) * slope;
  4095. refinedT = Math.min(1, Math.max(0, refinedT));
  4096. }
  4097. // Resolve cubic bezier for the given x
  4098. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4099. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4100. Math.pow(refinedT, 3);
  4101. };
  4102. return BezierCurve;
  4103. }());
  4104. BABYLON.BezierCurve = BezierCurve;
  4105. var Orientation;
  4106. (function (Orientation) {
  4107. Orientation[Orientation["CW"] = 0] = "CW";
  4108. Orientation[Orientation["CCW"] = 1] = "CCW";
  4109. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4110. var Angle = (function () {
  4111. /**
  4112. * Creates an Angle object of "radians" radians (float).
  4113. */
  4114. function Angle(radians) {
  4115. var _this = this;
  4116. /**
  4117. * Returns the Angle value in degrees (float).
  4118. */
  4119. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4120. /**
  4121. * Returns the Angle value in radians (float).
  4122. */
  4123. this.radians = function () { return _this._radians; };
  4124. this._radians = radians;
  4125. if (this._radians < 0.0)
  4126. this._radians += (2.0 * Math.PI);
  4127. }
  4128. /**
  4129. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4130. */
  4131. Angle.BetweenTwoPoints = function (a, b) {
  4132. var delta = b.subtract(a);
  4133. var theta = Math.atan2(delta.y, delta.x);
  4134. return new Angle(theta);
  4135. };
  4136. /**
  4137. * Returns a new Angle object from the passed float in radians.
  4138. */
  4139. Angle.FromRadians = function (radians) {
  4140. return new Angle(radians);
  4141. };
  4142. /**
  4143. * Returns a new Angle object from the passed float in degrees.
  4144. */
  4145. Angle.FromDegrees = function (degrees) {
  4146. return new Angle(degrees * Math.PI / 180.0);
  4147. };
  4148. return Angle;
  4149. }());
  4150. BABYLON.Angle = Angle;
  4151. var Arc2 = (function () {
  4152. /**
  4153. * Creates an Arc object from the three passed points : start, middle and end.
  4154. */
  4155. function Arc2(startPoint, midPoint, endPoint) {
  4156. this.startPoint = startPoint;
  4157. this.midPoint = midPoint;
  4158. this.endPoint = endPoint;
  4159. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4160. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4161. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4162. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4163. 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);
  4164. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4165. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4166. var a1 = this.startAngle.degrees();
  4167. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4168. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4169. // angles correction
  4170. if (a2 - a1 > +180.0)
  4171. a2 -= 360.0;
  4172. if (a2 - a1 < -180.0)
  4173. a2 += 360.0;
  4174. if (a3 - a2 > +180.0)
  4175. a3 -= 360.0;
  4176. if (a3 - a2 < -180.0)
  4177. a3 += 360.0;
  4178. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4179. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4180. }
  4181. return Arc2;
  4182. }());
  4183. BABYLON.Arc2 = Arc2;
  4184. var Path2 = (function () {
  4185. /**
  4186. * Creates a Path2 object from the starting 2D coordinates x and y.
  4187. */
  4188. function Path2(x, y) {
  4189. this._points = new Array();
  4190. this._length = 0.0;
  4191. this.closed = false;
  4192. this._points.push(new Vector2(x, y));
  4193. }
  4194. /**
  4195. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4196. * Returns the updated Path2.
  4197. */
  4198. Path2.prototype.addLineTo = function (x, y) {
  4199. if (closed) {
  4200. //Tools.Error("cannot add lines to closed paths");
  4201. return this;
  4202. }
  4203. var newPoint = new Vector2(x, y);
  4204. var previousPoint = this._points[this._points.length - 1];
  4205. this._points.push(newPoint);
  4206. this._length += newPoint.subtract(previousPoint).length();
  4207. return this;
  4208. };
  4209. /**
  4210. * 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.
  4211. * Returns the updated Path2.
  4212. */
  4213. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4214. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4215. if (closed) {
  4216. //Tools.Error("cannot add arcs to closed paths");
  4217. return this;
  4218. }
  4219. var startPoint = this._points[this._points.length - 1];
  4220. var midPoint = new Vector2(midX, midY);
  4221. var endPoint = new Vector2(endX, endY);
  4222. var arc = new Arc2(startPoint, midPoint, endPoint);
  4223. var increment = arc.angle.radians() / numberOfSegments;
  4224. if (arc.orientation === Orientation.CW)
  4225. increment *= -1;
  4226. var currentAngle = arc.startAngle.radians() + increment;
  4227. for (var i = 0; i < numberOfSegments; i++) {
  4228. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4229. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4230. this.addLineTo(x, y);
  4231. currentAngle += increment;
  4232. }
  4233. return this;
  4234. };
  4235. /**
  4236. * Closes the Path2.
  4237. * Returns the Path2.
  4238. */
  4239. Path2.prototype.close = function () {
  4240. this.closed = true;
  4241. return this;
  4242. };
  4243. /**
  4244. * Returns the Path2 total length (float).
  4245. */
  4246. Path2.prototype.length = function () {
  4247. var result = this._length;
  4248. if (!this.closed) {
  4249. var lastPoint = this._points[this._points.length - 1];
  4250. var firstPoint = this._points[0];
  4251. result += (firstPoint.subtract(lastPoint).length());
  4252. }
  4253. return result;
  4254. };
  4255. /**
  4256. * Returns the Path2 internal array of points.
  4257. */
  4258. Path2.prototype.getPoints = function () {
  4259. return this._points;
  4260. };
  4261. /**
  4262. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4263. */
  4264. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4265. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4266. //Tools.Error("normalized length position should be between 0 and 1.");
  4267. return Vector2.Zero();
  4268. }
  4269. var lengthPosition = normalizedLengthPosition * this.length();
  4270. var previousOffset = 0;
  4271. for (var i = 0; i < this._points.length; i++) {
  4272. var j = (i + 1) % this._points.length;
  4273. var a = this._points[i];
  4274. var b = this._points[j];
  4275. var bToA = b.subtract(a);
  4276. var nextOffset = (bToA.length() + previousOffset);
  4277. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4278. var dir = bToA.normalize();
  4279. var localOffset = lengthPosition - previousOffset;
  4280. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4281. }
  4282. previousOffset = nextOffset;
  4283. }
  4284. //Tools.Error("internal error");
  4285. return Vector2.Zero();
  4286. };
  4287. /**
  4288. * Returns a new Path2 starting at the coordinates (x, y).
  4289. */
  4290. Path2.StartingAt = function (x, y) {
  4291. return new Path2(x, y);
  4292. };
  4293. return Path2;
  4294. }());
  4295. BABYLON.Path2 = Path2;
  4296. var Path3D = (function () {
  4297. /**
  4298. * new Path3D(path, normal, raw)
  4299. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4300. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4301. * path : an array of Vector3, the curve axis of the Path3D
  4302. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4303. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4304. */
  4305. function Path3D(path, firstNormal, raw) {
  4306. this.path = path;
  4307. this._curve = new Array();
  4308. this._distances = new Array();
  4309. this._tangents = new Array();
  4310. this._normals = new Array();
  4311. this._binormals = new Array();
  4312. for (var p = 0; p < path.length; p++) {
  4313. this._curve[p] = path[p].clone(); // hard copy
  4314. }
  4315. this._raw = raw || false;
  4316. this._compute(firstNormal);
  4317. }
  4318. /**
  4319. * Returns the Path3D array of successive Vector3 designing its curve.
  4320. */
  4321. Path3D.prototype.getCurve = function () {
  4322. return this._curve;
  4323. };
  4324. /**
  4325. * Returns an array populated with tangent vectors on each Path3D curve point.
  4326. */
  4327. Path3D.prototype.getTangents = function () {
  4328. return this._tangents;
  4329. };
  4330. /**
  4331. * Returns an array populated with normal vectors on each Path3D curve point.
  4332. */
  4333. Path3D.prototype.getNormals = function () {
  4334. return this._normals;
  4335. };
  4336. /**
  4337. * Returns an array populated with binormal vectors on each Path3D curve point.
  4338. */
  4339. Path3D.prototype.getBinormals = function () {
  4340. return this._binormals;
  4341. };
  4342. /**
  4343. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4344. */
  4345. Path3D.prototype.getDistances = function () {
  4346. return this._distances;
  4347. };
  4348. /**
  4349. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4350. * Returns the same object updated.
  4351. */
  4352. Path3D.prototype.update = function (path, firstNormal) {
  4353. for (var p = 0; p < path.length; p++) {
  4354. this._curve[p].x = path[p].x;
  4355. this._curve[p].y = path[p].y;
  4356. this._curve[p].z = path[p].z;
  4357. }
  4358. this._compute(firstNormal);
  4359. return this;
  4360. };
  4361. // private function compute() : computes tangents, normals and binormals
  4362. Path3D.prototype._compute = function (firstNormal) {
  4363. var l = this._curve.length;
  4364. // first and last tangents
  4365. this._tangents[0] = this._getFirstNonNullVector(0);
  4366. if (!this._raw) {
  4367. this._tangents[0].normalize();
  4368. }
  4369. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4370. if (!this._raw) {
  4371. this._tangents[l - 1].normalize();
  4372. }
  4373. // normals and binormals at first point : arbitrary vector with _normalVector()
  4374. var tg0 = this._tangents[0];
  4375. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4376. this._normals[0] = pp0;
  4377. if (!this._raw) {
  4378. this._normals[0].normalize();
  4379. }
  4380. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4381. if (!this._raw) {
  4382. this._binormals[0].normalize();
  4383. }
  4384. this._distances[0] = 0.0;
  4385. // normals and binormals : next points
  4386. var prev; // previous vector (segment)
  4387. var cur; // current vector (segment)
  4388. var curTang; // current tangent
  4389. // previous normal
  4390. var prevBinor; // previous binormal
  4391. for (var i = 1; i < l; i++) {
  4392. // tangents
  4393. prev = this._getLastNonNullVector(i);
  4394. if (i < l - 1) {
  4395. cur = this._getFirstNonNullVector(i);
  4396. this._tangents[i] = prev.add(cur);
  4397. this._tangents[i].normalize();
  4398. }
  4399. this._distances[i] = this._distances[i - 1] + prev.length();
  4400. // normals and binormals
  4401. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4402. curTang = this._tangents[i];
  4403. prevBinor = this._binormals[i - 1];
  4404. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4405. if (!this._raw) {
  4406. this._normals[i].normalize();
  4407. }
  4408. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4409. if (!this._raw) {
  4410. this._binormals[i].normalize();
  4411. }
  4412. }
  4413. };
  4414. // private function getFirstNonNullVector(index)
  4415. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4416. Path3D.prototype._getFirstNonNullVector = function (index) {
  4417. var i = 1;
  4418. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4419. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4420. i++;
  4421. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4422. }
  4423. return nNVector;
  4424. };
  4425. // private function getLastNonNullVector(index)
  4426. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4427. Path3D.prototype._getLastNonNullVector = function (index) {
  4428. var i = 1;
  4429. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4430. while (nLVector.length() === 0 && index > i + 1) {
  4431. i++;
  4432. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4433. }
  4434. return nLVector;
  4435. };
  4436. // private function normalVector(v0, vt, va) :
  4437. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4438. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4439. Path3D.prototype._normalVector = function (v0, vt, va) {
  4440. var normal0;
  4441. var tgl = vt.length();
  4442. if (tgl === 0.0) {
  4443. tgl = 1.0;
  4444. }
  4445. if (va === undefined || va === null) {
  4446. var point;
  4447. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4448. point = new Vector3(0.0, -1.0, 0.0);
  4449. }
  4450. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4451. point = new Vector3(1.0, 0.0, 0.0);
  4452. }
  4453. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4454. point = new Vector3(0.0, 0.0, 1.0);
  4455. }
  4456. normal0 = Vector3.Cross(vt, point);
  4457. }
  4458. else {
  4459. normal0 = Vector3.Cross(vt, va);
  4460. Vector3.CrossToRef(normal0, vt, normal0);
  4461. }
  4462. normal0.normalize();
  4463. return normal0;
  4464. };
  4465. return Path3D;
  4466. }());
  4467. BABYLON.Path3D = Path3D;
  4468. var Curve3 = (function () {
  4469. /**
  4470. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4471. * A Curve3 is designed from a series of successive Vector3.
  4472. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4473. */
  4474. function Curve3(points) {
  4475. this._length = 0.0;
  4476. this._points = points;
  4477. this._length = this._computeLength(points);
  4478. }
  4479. /**
  4480. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4481. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4482. * @param v1 (Vector3) the control point
  4483. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4484. * @param nbPoints (integer) the wanted number of points in the curve
  4485. */
  4486. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4487. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4488. var bez = new Array();
  4489. var equation = function (t, val0, val1, val2) {
  4490. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4491. return res;
  4492. };
  4493. for (var i = 0; i <= nbPoints; i++) {
  4494. 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)));
  4495. }
  4496. return new Curve3(bez);
  4497. };
  4498. /**
  4499. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4500. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4501. * @param v1 (Vector3) the first control point
  4502. * @param v2 (Vector3) the second control point
  4503. * @param v3 (Vector3) the end point of the Cubic Bezier
  4504. * @param nbPoints (integer) the wanted number of points in the curve
  4505. */
  4506. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4507. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4508. var bez = new Array();
  4509. var equation = function (t, val0, val1, val2, val3) {
  4510. 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;
  4511. return res;
  4512. };
  4513. for (var i = 0; i <= nbPoints; i++) {
  4514. 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)));
  4515. }
  4516. return new Curve3(bez);
  4517. };
  4518. /**
  4519. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4520. * @param p1 (Vector3) the origin point of the Hermite Spline
  4521. * @param t1 (Vector3) the tangent vector at the origin point
  4522. * @param p2 (Vector3) the end point of the Hermite Spline
  4523. * @param t2 (Vector3) the tangent vector at the end point
  4524. * @param nbPoints (integer) the wanted number of points in the curve
  4525. */
  4526. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4527. var hermite = new Array();
  4528. var step = 1.0 / nbPoints;
  4529. for (var i = 0; i <= nbPoints; i++) {
  4530. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4531. }
  4532. return new Curve3(hermite);
  4533. };
  4534. /**
  4535. * Returns a Curve3 object along a CatmullRom Spline curve :
  4536. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4537. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4538. */
  4539. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4540. var totalPoints = new Array();
  4541. totalPoints.push(points[0].clone());
  4542. Array.prototype.push.apply(totalPoints, points);
  4543. totalPoints.push(points[points.length - 1].clone());
  4544. var catmullRom = new Array();
  4545. var step = 1.0 / nbPoints;
  4546. for (var i = 0; i < totalPoints.length - 3; i++) {
  4547. var amount = 0.0;
  4548. for (var c = 0; c < nbPoints; c++) {
  4549. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4550. amount += step;
  4551. }
  4552. }
  4553. i--;
  4554. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4555. return new Curve3(catmullRom);
  4556. };
  4557. /**
  4558. * Returns the Curve3 stored array of successive Vector3
  4559. */
  4560. Curve3.prototype.getPoints = function () {
  4561. return this._points;
  4562. };
  4563. /**
  4564. * Returns the computed length (float) of the curve.
  4565. */
  4566. Curve3.prototype.length = function () {
  4567. return this._length;
  4568. };
  4569. /**
  4570. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4571. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4572. * curveA and curveB keep unchanged.
  4573. */
  4574. Curve3.prototype.continue = function (curve) {
  4575. var lastPoint = this._points[this._points.length - 1];
  4576. var continuedPoints = this._points.slice();
  4577. var curvePoints = curve.getPoints();
  4578. for (var i = 1; i < curvePoints.length; i++) {
  4579. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4580. }
  4581. var continuedCurve = new Curve3(continuedPoints);
  4582. return continuedCurve;
  4583. };
  4584. Curve3.prototype._computeLength = function (path) {
  4585. var l = 0;
  4586. for (var i = 1; i < path.length; i++) {
  4587. l += (path[i].subtract(path[i - 1])).length();
  4588. }
  4589. return l;
  4590. };
  4591. return Curve3;
  4592. }());
  4593. BABYLON.Curve3 = Curve3;
  4594. // SphericalHarmonics
  4595. var SphericalHarmonics = (function () {
  4596. function SphericalHarmonics() {
  4597. this.L00 = Vector3.Zero();
  4598. this.L1_1 = Vector3.Zero();
  4599. this.L10 = Vector3.Zero();
  4600. this.L11 = Vector3.Zero();
  4601. this.L2_2 = Vector3.Zero();
  4602. this.L2_1 = Vector3.Zero();
  4603. this.L20 = Vector3.Zero();
  4604. this.L21 = Vector3.Zero();
  4605. this.L22 = Vector3.Zero();
  4606. }
  4607. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4608. var colorVector = new Vector3(color.r, color.g, color.b);
  4609. var c = colorVector.scale(deltaSolidAngle);
  4610. this.L00 = this.L00.add(c.scale(0.282095));
  4611. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4612. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4613. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4614. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4615. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4616. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4617. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4618. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4619. };
  4620. SphericalHarmonics.prototype.scale = function (scale) {
  4621. this.L00 = this.L00.scale(scale);
  4622. this.L1_1 = this.L1_1.scale(scale);
  4623. this.L10 = this.L10.scale(scale);
  4624. this.L11 = this.L11.scale(scale);
  4625. this.L2_2 = this.L2_2.scale(scale);
  4626. this.L2_1 = this.L2_1.scale(scale);
  4627. this.L20 = this.L20.scale(scale);
  4628. this.L21 = this.L21.scale(scale);
  4629. this.L22 = this.L22.scale(scale);
  4630. };
  4631. return SphericalHarmonics;
  4632. }());
  4633. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4634. // SphericalPolynomial
  4635. var SphericalPolynomial = (function () {
  4636. function SphericalPolynomial() {
  4637. this.x = Vector3.Zero();
  4638. this.y = Vector3.Zero();
  4639. this.z = Vector3.Zero();
  4640. this.xx = Vector3.Zero();
  4641. this.yy = Vector3.Zero();
  4642. this.zz = Vector3.Zero();
  4643. this.xy = Vector3.Zero();
  4644. this.yz = Vector3.Zero();
  4645. this.zx = Vector3.Zero();
  4646. }
  4647. SphericalPolynomial.prototype.addAmbient = function (color) {
  4648. var colorVector = new Vector3(color.r, color.g, color.b);
  4649. this.xx = this.xx.add(colorVector);
  4650. this.yy = this.yy.add(colorVector);
  4651. this.zz = this.zz.add(colorVector);
  4652. };
  4653. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4654. var result = new SphericalPolynomial();
  4655. result.x = harmonics.L11.scale(1.02333);
  4656. result.y = harmonics.L1_1.scale(1.02333);
  4657. result.z = harmonics.L10.scale(1.02333);
  4658. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4659. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4660. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4661. result.yz = harmonics.L2_1.scale(0.858086);
  4662. result.zx = harmonics.L21.scale(0.858086);
  4663. result.xy = harmonics.L2_2.scale(0.858086);
  4664. return result;
  4665. };
  4666. return SphericalPolynomial;
  4667. }());
  4668. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4669. // Vertex formats
  4670. var PositionNormalVertex = (function () {
  4671. function PositionNormalVertex(position, normal) {
  4672. if (position === void 0) { position = Vector3.Zero(); }
  4673. if (normal === void 0) { normal = Vector3.Up(); }
  4674. this.position = position;
  4675. this.normal = normal;
  4676. }
  4677. PositionNormalVertex.prototype.clone = function () {
  4678. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4679. };
  4680. return PositionNormalVertex;
  4681. }());
  4682. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4683. var PositionNormalTextureVertex = (function () {
  4684. function PositionNormalTextureVertex(position, normal, uv) {
  4685. if (position === void 0) { position = Vector3.Zero(); }
  4686. if (normal === void 0) { normal = Vector3.Up(); }
  4687. if (uv === void 0) { uv = Vector2.Zero(); }
  4688. this.position = position;
  4689. this.normal = normal;
  4690. this.uv = uv;
  4691. }
  4692. PositionNormalTextureVertex.prototype.clone = function () {
  4693. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4694. };
  4695. return PositionNormalTextureVertex;
  4696. }());
  4697. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4698. // Temporary pre-allocated objects for engine internal use
  4699. // usage in any internal function :
  4700. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4701. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4702. var Tmp = (function () {
  4703. function Tmp() {
  4704. }
  4705. return Tmp;
  4706. }());
  4707. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4708. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4709. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4710. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4711. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4712. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4713. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4714. Matrix.Zero(), Matrix.Zero(),
  4715. Matrix.Zero(), Matrix.Zero(),
  4716. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4717. BABYLON.Tmp = Tmp;
  4718. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4719. var MathTmp = (function () {
  4720. function MathTmp() {
  4721. }
  4722. return MathTmp;
  4723. }());
  4724. MathTmp.Vector3 = [Vector3.Zero()];
  4725. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4726. MathTmp.Quaternion = [Quaternion.Zero()];
  4727. })(BABYLON || (BABYLON = {}));
  4728. //# sourceMappingURL=babylon.math.js.map
  4729. //# sourceMappingURL=babylon.mixins.js.map
  4730. var BABYLON;
  4731. (function (BABYLON) {
  4732. function generateSerializableMember(type, sourceName) {
  4733. return function (target, propertyKey) {
  4734. if (!target.__serializableMembers) {
  4735. target.__serializableMembers = {};
  4736. }
  4737. if (!target.__serializableMembers[propertyKey]) {
  4738. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4739. }
  4740. };
  4741. }
  4742. function generateExpandMember(setCallback, targetKey) {
  4743. return function (target, propertyKey) {
  4744. var key = targetKey || ("_" + propertyKey);
  4745. Object.defineProperty(target, propertyKey, {
  4746. get: function () {
  4747. return this[key];
  4748. },
  4749. set: function (value) {
  4750. if (this[key] === value) {
  4751. return;
  4752. }
  4753. this[key] = value;
  4754. if (setCallback) {
  4755. target[setCallback].apply(this);
  4756. }
  4757. },
  4758. enumerable: true,
  4759. configurable: true
  4760. });
  4761. };
  4762. }
  4763. function expandToProperty(callback, targetKey) {
  4764. return generateExpandMember(callback, targetKey);
  4765. }
  4766. BABYLON.expandToProperty = expandToProperty;
  4767. function serialize(sourceName) {
  4768. return generateSerializableMember(0, sourceName); // value member
  4769. }
  4770. BABYLON.serialize = serialize;
  4771. function serializeAsTexture(sourceName) {
  4772. return generateSerializableMember(1, sourceName); // texture member
  4773. }
  4774. BABYLON.serializeAsTexture = serializeAsTexture;
  4775. function serializeAsColor3(sourceName) {
  4776. return generateSerializableMember(2, sourceName); // color3 member
  4777. }
  4778. BABYLON.serializeAsColor3 = serializeAsColor3;
  4779. function serializeAsFresnelParameters(sourceName) {
  4780. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4781. }
  4782. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4783. function serializeAsVector2(sourceName) {
  4784. return generateSerializableMember(4, sourceName); // vector2 member
  4785. }
  4786. BABYLON.serializeAsVector2 = serializeAsVector2;
  4787. function serializeAsVector3(sourceName) {
  4788. return generateSerializableMember(5, sourceName); // vector3 member
  4789. }
  4790. BABYLON.serializeAsVector3 = serializeAsVector3;
  4791. function serializeAsMeshReference(sourceName) {
  4792. return generateSerializableMember(6, sourceName); // mesh reference member
  4793. }
  4794. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4795. function serializeAsColorCurves(sourceName) {
  4796. return generateSerializableMember(7, sourceName); // color curves
  4797. }
  4798. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4799. var SerializationHelper = (function () {
  4800. function SerializationHelper() {
  4801. }
  4802. SerializationHelper.Serialize = function (entity, serializationObject) {
  4803. if (!serializationObject) {
  4804. serializationObject = {};
  4805. }
  4806. // Tags
  4807. if (BABYLON.Tags) {
  4808. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4809. }
  4810. // Properties
  4811. for (var property in entity.__serializableMembers) {
  4812. var propertyDescriptor = entity.__serializableMembers[property];
  4813. var targetPropertyName = propertyDescriptor.sourceName || property;
  4814. var propertyType = propertyDescriptor.type;
  4815. var sourceProperty = entity[property];
  4816. if (sourceProperty !== undefined && sourceProperty !== null) {
  4817. switch (propertyType) {
  4818. case 0:
  4819. serializationObject[targetPropertyName] = sourceProperty;
  4820. break;
  4821. case 1:
  4822. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4823. break;
  4824. case 2:
  4825. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4826. break;
  4827. case 3:
  4828. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4829. break;
  4830. case 4:
  4831. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4832. break;
  4833. case 5:
  4834. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4835. break;
  4836. case 6:
  4837. serializationObject[targetPropertyName] = sourceProperty.id;
  4838. break;
  4839. case 7:
  4840. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4841. break;
  4842. }
  4843. }
  4844. }
  4845. return serializationObject;
  4846. };
  4847. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4848. var destination = creationFunction();
  4849. // Tags
  4850. if (BABYLON.Tags) {
  4851. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4852. }
  4853. // Properties
  4854. for (var property in destination.__serializableMembers) {
  4855. var propertyDescriptor = destination.__serializableMembers[property];
  4856. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4857. var propertyType = propertyDescriptor.type;
  4858. if (sourceProperty !== undefined && sourceProperty !== null) {
  4859. switch (propertyType) {
  4860. case 0:
  4861. destination[property] = sourceProperty;
  4862. break;
  4863. case 1:
  4864. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4865. break;
  4866. case 2:
  4867. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4868. break;
  4869. case 3:
  4870. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4871. break;
  4872. case 4:
  4873. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4874. break;
  4875. case 5:
  4876. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4877. break;
  4878. case 6:
  4879. destination[property] = scene.getLastMeshByID(sourceProperty);
  4880. break;
  4881. case 7:
  4882. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4883. break;
  4884. }
  4885. }
  4886. }
  4887. return destination;
  4888. };
  4889. SerializationHelper.Clone = function (creationFunction, source) {
  4890. var destination = creationFunction();
  4891. // Tags
  4892. if (BABYLON.Tags) {
  4893. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4894. }
  4895. // Properties
  4896. for (var property in destination.__serializableMembers) {
  4897. var propertyDescriptor = destination.__serializableMembers[property];
  4898. var sourceProperty = source[property];
  4899. var propertyType = propertyDescriptor.type;
  4900. if (sourceProperty !== undefined && sourceProperty !== null) {
  4901. switch (propertyType) {
  4902. case 0: // Value
  4903. case 6:
  4904. destination[property] = sourceProperty;
  4905. break;
  4906. case 1: // Texture
  4907. case 2: // Color3
  4908. case 3: // FresnelParameters
  4909. case 4: // Vector2
  4910. case 5: // Vector3
  4911. case 7:
  4912. destination[property] = sourceProperty.clone();
  4913. break;
  4914. }
  4915. }
  4916. }
  4917. return destination;
  4918. };
  4919. return SerializationHelper;
  4920. }());
  4921. BABYLON.SerializationHelper = SerializationHelper;
  4922. })(BABYLON || (BABYLON = {}));
  4923. //# sourceMappingURL=babylon.decorators.js.map
  4924. var BABYLON;
  4925. (function (BABYLON) {
  4926. /**
  4927. * A class serves as a medium between the observable and its observers
  4928. */
  4929. var EventState = (function () {
  4930. /**
  4931. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4932. */
  4933. function EventState(mask, skipNextObservers) {
  4934. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4935. this.initalize(mask, skipNextObservers);
  4936. }
  4937. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4938. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4939. this.mask = mask;
  4940. this.skipNextObservers = skipNextObservers;
  4941. return this;
  4942. };
  4943. return EventState;
  4944. }());
  4945. BABYLON.EventState = EventState;
  4946. /**
  4947. * Represent an Observer registered to a given Observable object.
  4948. */
  4949. var Observer = (function () {
  4950. function Observer(callback, mask) {
  4951. this.callback = callback;
  4952. this.mask = mask;
  4953. }
  4954. return Observer;
  4955. }());
  4956. BABYLON.Observer = Observer;
  4957. /**
  4958. * The Observable class is a simple implementation of the Observable pattern.
  4959. * 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.
  4960. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4961. * 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).
  4962. * 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.
  4963. */
  4964. var Observable = (function () {
  4965. function Observable() {
  4966. this._observers = new Array();
  4967. this._eventState = new EventState(0);
  4968. }
  4969. /**
  4970. * Create a new Observer with the specified callback
  4971. * @param callback the callback that will be executed for that Observer
  4972. * @param mask the mask used to filter observers
  4973. * @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.
  4974. */
  4975. Observable.prototype.add = function (callback, mask, insertFirst) {
  4976. if (mask === void 0) { mask = -1; }
  4977. if (insertFirst === void 0) { insertFirst = false; }
  4978. if (!callback) {
  4979. return null;
  4980. }
  4981. var observer = new Observer(callback, mask);
  4982. if (insertFirst) {
  4983. this._observers.unshift(observer);
  4984. }
  4985. else {
  4986. this._observers.push(observer);
  4987. }
  4988. return observer;
  4989. };
  4990. /**
  4991. * Remove an Observer from the Observable object
  4992. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4993. */
  4994. Observable.prototype.remove = function (observer) {
  4995. var index = this._observers.indexOf(observer);
  4996. if (index !== -1) {
  4997. this._observers.splice(index, 1);
  4998. return true;
  4999. }
  5000. return false;
  5001. };
  5002. /**
  5003. * Remove a callback from the Observable object
  5004. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5005. */
  5006. Observable.prototype.removeCallback = function (callback) {
  5007. for (var index = 0; index < this._observers.length; index++) {
  5008. if (this._observers[index].callback === callback) {
  5009. this._observers.splice(index, 1);
  5010. return true;
  5011. }
  5012. }
  5013. return false;
  5014. };
  5015. /**
  5016. * Notify all Observers by calling their respective callback with the given data
  5017. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5018. * @param eventData
  5019. * @param mask
  5020. */
  5021. Observable.prototype.notifyObservers = function (eventData, mask) {
  5022. if (mask === void 0) { mask = -1; }
  5023. var state = this._eventState;
  5024. state.mask = mask;
  5025. state.skipNextObservers = false;
  5026. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5027. var obs = _a[_i];
  5028. if (obs.mask & mask) {
  5029. obs.callback(eventData, state);
  5030. }
  5031. if (state.skipNextObservers) {
  5032. return false;
  5033. }
  5034. }
  5035. return true;
  5036. };
  5037. /**
  5038. * return true is the Observable has at least one Observer registered
  5039. */
  5040. Observable.prototype.hasObservers = function () {
  5041. return this._observers.length > 0;
  5042. };
  5043. /**
  5044. * Clear the list of observers
  5045. */
  5046. Observable.prototype.clear = function () {
  5047. this._observers = new Array();
  5048. };
  5049. /**
  5050. * Clone the current observable
  5051. */
  5052. Observable.prototype.clone = function () {
  5053. var result = new Observable();
  5054. result._observers = this._observers.slice(0);
  5055. return result;
  5056. };
  5057. /**
  5058. * Does this observable handles observer registered with a given mask
  5059. * @param {number} trigger - the mask to be tested
  5060. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5061. **/
  5062. Observable.prototype.hasSpecificMask = function (mask) {
  5063. if (mask === void 0) { mask = -1; }
  5064. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5065. var obs = _a[_i];
  5066. if (obs.mask & mask && obs.mask === mask) {
  5067. return true;
  5068. }
  5069. }
  5070. return false;
  5071. };
  5072. return Observable;
  5073. }());
  5074. BABYLON.Observable = Observable;
  5075. })(BABYLON || (BABYLON = {}));
  5076. //# sourceMappingURL=babylon.observable.js.map
  5077. var BABYLON;
  5078. (function (BABYLON) {
  5079. var SmartArray = (function () {
  5080. function SmartArray(capacity) {
  5081. this.length = 0;
  5082. this._duplicateId = 0;
  5083. this.data = new Array(capacity);
  5084. this._id = SmartArray._GlobalId++;
  5085. }
  5086. SmartArray.prototype.push = function (value) {
  5087. this.data[this.length++] = value;
  5088. if (this.length > this.data.length) {
  5089. this.data.length *= 2;
  5090. }
  5091. if (!value.__smartArrayFlags) {
  5092. value.__smartArrayFlags = {};
  5093. }
  5094. value.__smartArrayFlags[this._id] = this._duplicateId;
  5095. };
  5096. SmartArray.prototype.forEach = function (func) {
  5097. for (var index = 0; index < this.length; index++) {
  5098. func(this.data[index]);
  5099. }
  5100. };
  5101. SmartArray.prototype.pushNoDuplicate = function (value) {
  5102. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5103. return false;
  5104. }
  5105. this.push(value);
  5106. return true;
  5107. };
  5108. SmartArray.prototype.sort = function (compareFn) {
  5109. this.data.sort(compareFn);
  5110. };
  5111. SmartArray.prototype.reset = function () {
  5112. this.length = 0;
  5113. this._duplicateId++;
  5114. };
  5115. SmartArray.prototype.dispose = function () {
  5116. this.reset();
  5117. this.data.length = 0;
  5118. };
  5119. SmartArray.prototype.concat = function (array) {
  5120. if (array.length === 0) {
  5121. return;
  5122. }
  5123. if (this.length + array.length > this.data.length) {
  5124. this.data.length = (this.length + array.length) * 2;
  5125. }
  5126. for (var index = 0; index < array.length; index++) {
  5127. this.data[this.length++] = (array.data || array)[index];
  5128. }
  5129. };
  5130. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5131. if (array.length === 0) {
  5132. return;
  5133. }
  5134. if (this.length + array.length > this.data.length) {
  5135. this.data.length = (this.length + array.length) * 2;
  5136. }
  5137. for (var index = 0; index < array.length; index++) {
  5138. var item = (array.data || array)[index];
  5139. this.pushNoDuplicate(item);
  5140. }
  5141. };
  5142. SmartArray.prototype.indexOf = function (value) {
  5143. var position = this.data.indexOf(value);
  5144. if (position >= this.length) {
  5145. return -1;
  5146. }
  5147. return position;
  5148. };
  5149. SmartArray.prototype.contains = function (value) {
  5150. return this.data.indexOf(value) !== -1;
  5151. };
  5152. return SmartArray;
  5153. }());
  5154. // Statics
  5155. SmartArray._GlobalId = 0;
  5156. BABYLON.SmartArray = SmartArray;
  5157. })(BABYLON || (BABYLON = {}));
  5158. //# sourceMappingURL=babylon.smartArray.js.map
  5159. var BABYLON;
  5160. (function (BABYLON) {
  5161. // Screenshots
  5162. var screenshotCanvas;
  5163. var cloneValue = function (source, destinationObject) {
  5164. if (!source)
  5165. return null;
  5166. if (source instanceof BABYLON.Mesh) {
  5167. return null;
  5168. }
  5169. if (source instanceof BABYLON.SubMesh) {
  5170. return source.clone(destinationObject);
  5171. }
  5172. else if (source.clone) {
  5173. return source.clone();
  5174. }
  5175. return null;
  5176. };
  5177. var Tools = (function () {
  5178. function Tools() {
  5179. }
  5180. ;
  5181. /**
  5182. * Interpolates between a and b via alpha
  5183. * @param a The lower value (returned when alpha = 0)
  5184. * @param b The upper value (returned when alpha = 1)
  5185. * @param alpha The interpolation-factor
  5186. * @return The mixed value
  5187. */
  5188. Tools.Mix = function (a, b, alpha) {
  5189. return a * (1 - alpha) + b * alpha;
  5190. };
  5191. Tools.Instantiate = function (className) {
  5192. var arr = className.split(".");
  5193. var fn = (window || this);
  5194. for (var i = 0, len = arr.length; i < len; i++) {
  5195. fn = fn[arr[i]];
  5196. }
  5197. if (typeof fn !== "function") {
  5198. return null;
  5199. }
  5200. return fn;
  5201. };
  5202. Tools.SetImmediate = function (action) {
  5203. if (window.setImmediate) {
  5204. window.setImmediate(action);
  5205. }
  5206. else {
  5207. setTimeout(action, 1);
  5208. }
  5209. };
  5210. Tools.IsExponentOfTwo = function (value) {
  5211. var count = 1;
  5212. do {
  5213. count *= 2;
  5214. } while (count < value);
  5215. return count === value;
  5216. };
  5217. /**
  5218. * Find the next highest power of two.
  5219. * @param x Number to start search from.
  5220. * @return Next highest power of two.
  5221. */
  5222. Tools.CeilingPOT = function (x) {
  5223. x--;
  5224. x |= x >> 1;
  5225. x |= x >> 2;
  5226. x |= x >> 4;
  5227. x |= x >> 8;
  5228. x |= x >> 16;
  5229. x++;
  5230. return x;
  5231. };
  5232. /**
  5233. * Find the next lowest power of two.
  5234. * @param x Number to start search from.
  5235. * @return Next lowest power of two.
  5236. */
  5237. Tools.FloorPOT = function (x) {
  5238. x = x | (x >> 1);
  5239. x = x | (x >> 2);
  5240. x = x | (x >> 4);
  5241. x = x | (x >> 8);
  5242. x = x | (x >> 16);
  5243. return x - (x >> 1);
  5244. };
  5245. /**
  5246. * Find the nearest power of two.
  5247. * @param x Number to start search from.
  5248. * @return Next nearest power of two.
  5249. */
  5250. Tools.NearestPOT = function (x) {
  5251. var c = Tools.CeilingPOT(x);
  5252. var f = Tools.FloorPOT(x);
  5253. return (c - x) > (x - f) ? f : c;
  5254. };
  5255. Tools.GetExponentOfTwo = function (value, max, mode) {
  5256. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5257. var pot;
  5258. switch (mode) {
  5259. case BABYLON.Engine.SCALEMODE_FLOOR:
  5260. pot = Tools.FloorPOT(value);
  5261. break;
  5262. case BABYLON.Engine.SCALEMODE_NEAREST:
  5263. pot = Tools.NearestPOT(value);
  5264. break;
  5265. case BABYLON.Engine.SCALEMODE_CEILING:
  5266. pot = Tools.CeilingPOT(value);
  5267. break;
  5268. }
  5269. return Math.min(pot, max);
  5270. };
  5271. Tools.GetFilename = function (path) {
  5272. var index = path.lastIndexOf("/");
  5273. if (index < 0)
  5274. return path;
  5275. return path.substring(index + 1);
  5276. };
  5277. Tools.GetDOMTextContent = function (element) {
  5278. var result = "";
  5279. var child = element.firstChild;
  5280. while (child) {
  5281. if (child.nodeType === 3) {
  5282. result += child.textContent;
  5283. }
  5284. child = child.nextSibling;
  5285. }
  5286. return result;
  5287. };
  5288. Tools.ToDegrees = function (angle) {
  5289. return angle * 180 / Math.PI;
  5290. };
  5291. Tools.ToRadians = function (angle) {
  5292. return angle * Math.PI / 180;
  5293. };
  5294. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5295. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5296. var output = "";
  5297. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5298. var i = 0;
  5299. var bytes = new Uint8Array(buffer);
  5300. while (i < bytes.length) {
  5301. chr1 = bytes[i++];
  5302. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5303. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5304. enc1 = chr1 >> 2;
  5305. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5306. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5307. enc4 = chr3 & 63;
  5308. if (isNaN(chr2)) {
  5309. enc3 = enc4 = 64;
  5310. }
  5311. else if (isNaN(chr3)) {
  5312. enc4 = 64;
  5313. }
  5314. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5315. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5316. }
  5317. return "data:image/png;base64," + output;
  5318. };
  5319. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5320. if (bias === void 0) { bias = null; }
  5321. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5322. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5323. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5324. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5325. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5326. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5327. }
  5328. if (bias) {
  5329. minimum.x -= minimum.x * bias.x + bias.y;
  5330. minimum.y -= minimum.y * bias.x + bias.y;
  5331. minimum.z -= minimum.z * bias.x + bias.y;
  5332. maximum.x += maximum.x * bias.x + bias.y;
  5333. maximum.y += maximum.y * bias.x + bias.y;
  5334. maximum.z += maximum.z * bias.x + bias.y;
  5335. }
  5336. return {
  5337. minimum: minimum,
  5338. maximum: maximum
  5339. };
  5340. };
  5341. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5342. if (bias === void 0) { bias = null; }
  5343. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5344. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5345. if (!stride) {
  5346. stride = 3;
  5347. }
  5348. for (var index = start; index < start + count; index++) {
  5349. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5350. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5351. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5352. }
  5353. if (bias) {
  5354. minimum.x -= minimum.x * bias.x + bias.y;
  5355. minimum.y -= minimum.y * bias.x + bias.y;
  5356. minimum.z -= minimum.z * bias.x + bias.y;
  5357. maximum.x += maximum.x * bias.x + bias.y;
  5358. maximum.y += maximum.y * bias.x + bias.y;
  5359. maximum.z += maximum.z * bias.x + bias.y;
  5360. }
  5361. return {
  5362. minimum: minimum,
  5363. maximum: maximum
  5364. };
  5365. };
  5366. Tools.Vector2ArrayFeeder = function (array) {
  5367. return function (index) {
  5368. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5369. var length = isFloatArray ? array.length / 2 : array.length;
  5370. if (index >= length) {
  5371. return null;
  5372. }
  5373. if (isFloatArray) {
  5374. var fa = array;
  5375. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5376. }
  5377. var a = array;
  5378. return a[index];
  5379. };
  5380. };
  5381. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5382. if (bias === void 0) { bias = null; }
  5383. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5384. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5385. var i = 0;
  5386. var cur = feeder(i++);
  5387. while (cur) {
  5388. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5389. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5390. cur = feeder(i++);
  5391. }
  5392. if (bias) {
  5393. minimum.x -= minimum.x * bias.x + bias.y;
  5394. minimum.y -= minimum.y * bias.x + bias.y;
  5395. maximum.x += maximum.x * bias.x + bias.y;
  5396. maximum.y += maximum.y * bias.x + bias.y;
  5397. }
  5398. return {
  5399. minimum: minimum,
  5400. maximum: maximum
  5401. };
  5402. };
  5403. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5404. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5405. return undefined;
  5406. return Array.isArray(obj) ? obj : [obj];
  5407. };
  5408. // Misc.
  5409. Tools.GetPointerPrefix = function () {
  5410. var eventPrefix = "pointer";
  5411. // Check if pointer events are supported
  5412. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5413. eventPrefix = "mouse";
  5414. }
  5415. return eventPrefix;
  5416. };
  5417. /**
  5418. * @param func - the function to be called
  5419. * @param requester - the object that will request the next frame. Falls back to window.
  5420. */
  5421. Tools.QueueNewFrame = function (func, requester) {
  5422. if (requester === void 0) { requester = window; }
  5423. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5424. /*if(requester.isPresenting) {
  5425. return;
  5426. } else*/ if (requester.requestAnimationFrame)
  5427. requester.requestAnimationFrame(func);
  5428. else if (requester.msRequestAnimationFrame)
  5429. requester.msRequestAnimationFrame(func);
  5430. else if (requester.webkitRequestAnimationFrame)
  5431. requester.webkitRequestAnimationFrame(func);
  5432. else if (requester.mozRequestAnimationFrame)
  5433. requester.mozRequestAnimationFrame(func);
  5434. else if (requester.oRequestAnimationFrame)
  5435. requester.oRequestAnimationFrame(func);
  5436. else {
  5437. window.setTimeout(func, 16);
  5438. }
  5439. };
  5440. Tools.RequestFullscreen = function (element) {
  5441. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5442. if (!requestFunction)
  5443. return;
  5444. requestFunction.call(element);
  5445. };
  5446. Tools.ExitFullscreen = function () {
  5447. if (document.exitFullscreen) {
  5448. document.exitFullscreen();
  5449. }
  5450. else if (document.mozCancelFullScreen) {
  5451. document.mozCancelFullScreen();
  5452. }
  5453. else if (document.webkitCancelFullScreen) {
  5454. document.webkitCancelFullScreen();
  5455. }
  5456. else if (document.msCancelFullScreen) {
  5457. document.msCancelFullScreen();
  5458. }
  5459. };
  5460. Tools.SetCorsBehavior = function (url, img) {
  5461. if (Tools.CorsBehavior) {
  5462. switch (typeof (Tools.CorsBehavior)) {
  5463. case "function":
  5464. var result = Tools.CorsBehavior(url);
  5465. if (result) {
  5466. img.crossOrigin = result;
  5467. }
  5468. break;
  5469. case "string":
  5470. default:
  5471. img.crossOrigin = Tools.CorsBehavior;
  5472. break;
  5473. }
  5474. }
  5475. };
  5476. // External files
  5477. Tools.CleanUrl = function (url) {
  5478. url = url.replace(/#/mg, "%23");
  5479. return url;
  5480. };
  5481. Tools.LoadImage = function (url, onload, onerror, database) {
  5482. if (url instanceof ArrayBuffer) {
  5483. url = Tools.EncodeArrayBufferTobase64(url);
  5484. }
  5485. url = Tools.CleanUrl(url);
  5486. var img = new Image();
  5487. if (url.substr(0, 5) !== "data:") {
  5488. Tools.SetCorsBehavior(url, img);
  5489. }
  5490. img.onload = function () {
  5491. onload(img);
  5492. };
  5493. img.onerror = function (err) {
  5494. Tools.Error("Error while trying to load image: " + url);
  5495. if (Tools.UseFallbackTexture) {
  5496. img.src = Tools.fallbackTexture;
  5497. onload(img);
  5498. }
  5499. else {
  5500. onerror();
  5501. }
  5502. };
  5503. var noIndexedDB = function () {
  5504. img.src = url;
  5505. };
  5506. var loadFromIndexedDB = function () {
  5507. database.loadImageFromDB(url, img);
  5508. };
  5509. //ANY database to do!
  5510. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5511. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5512. }
  5513. else {
  5514. if (url.indexOf("file:") !== 0) {
  5515. noIndexedDB();
  5516. }
  5517. else {
  5518. var textureName = url.substring(5).toLowerCase();
  5519. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5520. try {
  5521. var blobURL;
  5522. try {
  5523. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5524. }
  5525. catch (ex) {
  5526. // Chrome doesn't support oneTimeOnly parameter
  5527. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5528. }
  5529. img.src = blobURL;
  5530. }
  5531. catch (e) {
  5532. img.src = null;
  5533. }
  5534. }
  5535. else {
  5536. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5537. img.src = Tools.fallbackTexture;
  5538. }
  5539. }
  5540. }
  5541. return img;
  5542. };
  5543. //ANY
  5544. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5545. url = Tools.CleanUrl(url);
  5546. var noIndexedDB = function () {
  5547. var request = new XMLHttpRequest();
  5548. var loadUrl = Tools.BaseUrl + url;
  5549. request.open('GET', loadUrl, true);
  5550. if (useArrayBuffer) {
  5551. request.responseType = "arraybuffer";
  5552. }
  5553. request.onprogress = progressCallBack;
  5554. request.onreadystatechange = function () {
  5555. // In case of undefined state in some browsers.
  5556. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5557. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5558. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5559. callback(!useArrayBuffer ? request.responseText : request.response);
  5560. }
  5561. else {
  5562. if (onError) {
  5563. onError(request);
  5564. }
  5565. else {
  5566. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5567. }
  5568. }
  5569. }
  5570. };
  5571. request.send(null);
  5572. };
  5573. var loadFromIndexedDB = function () {
  5574. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5575. };
  5576. if (url.indexOf("file:") !== -1) {
  5577. var fileName = url.substring(5).toLowerCase();
  5578. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5579. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5580. }
  5581. else {
  5582. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5583. }
  5584. }
  5585. else {
  5586. // Caching all files
  5587. if (database && database.enableSceneOffline) {
  5588. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5589. }
  5590. else {
  5591. noIndexedDB();
  5592. }
  5593. }
  5594. };
  5595. /**
  5596. * Load a script (identified by an url). When the url returns, the
  5597. * content of this file is added into a new script element, attached to the DOM (body element)
  5598. */
  5599. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5600. var head = document.getElementsByTagName('head')[0];
  5601. var script = document.createElement('script');
  5602. script.type = 'text/javascript';
  5603. script.src = scriptUrl;
  5604. var self = this;
  5605. script.onload = function () {
  5606. if (onSuccess) {
  5607. onSuccess();
  5608. }
  5609. };
  5610. script.onerror = function () {
  5611. if (onError) {
  5612. onError();
  5613. }
  5614. };
  5615. head.appendChild(script);
  5616. };
  5617. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5618. var reader = new FileReader();
  5619. reader.onload = function (e) {
  5620. //target doesn't have result from ts 1.3
  5621. callback(e.target['result']);
  5622. };
  5623. reader.onprogress = progressCallback;
  5624. reader.readAsDataURL(fileToLoad);
  5625. };
  5626. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5627. var reader = new FileReader();
  5628. reader.onerror = function (e) {
  5629. Tools.Log("Error while reading file: " + fileToLoad.name);
  5630. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5631. };
  5632. reader.onload = function (e) {
  5633. //target doesn't have result from ts 1.3
  5634. callback(e.target['result']);
  5635. };
  5636. reader.onprogress = progressCallBack;
  5637. if (!useArrayBuffer) {
  5638. // Asynchronous read
  5639. reader.readAsText(fileToLoad);
  5640. }
  5641. else {
  5642. reader.readAsArrayBuffer(fileToLoad);
  5643. }
  5644. };
  5645. //returns a downloadable url to a file content.
  5646. Tools.FileAsURL = function (content) {
  5647. var fileBlob = new Blob([content]);
  5648. var url = window.URL || window.webkitURL;
  5649. var link = url.createObjectURL(fileBlob);
  5650. return link;
  5651. };
  5652. // Misc.
  5653. Tools.Format = function (value, decimals) {
  5654. if (decimals === void 0) { decimals = 2; }
  5655. return value.toFixed(decimals);
  5656. };
  5657. Tools.CheckExtends = function (v, min, max) {
  5658. if (v.x < min.x)
  5659. min.x = v.x;
  5660. if (v.y < min.y)
  5661. min.y = v.y;
  5662. if (v.z < min.z)
  5663. min.z = v.z;
  5664. if (v.x > max.x)
  5665. max.x = v.x;
  5666. if (v.y > max.y)
  5667. max.y = v.y;
  5668. if (v.z > max.z)
  5669. max.z = v.z;
  5670. };
  5671. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5672. for (var prop in source) {
  5673. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5674. continue;
  5675. }
  5676. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5677. continue;
  5678. }
  5679. var sourceValue = source[prop];
  5680. var typeOfSourceValue = typeof sourceValue;
  5681. if (typeOfSourceValue === "function") {
  5682. continue;
  5683. }
  5684. if (typeOfSourceValue === "object") {
  5685. if (sourceValue instanceof Array) {
  5686. destination[prop] = [];
  5687. if (sourceValue.length > 0) {
  5688. if (typeof sourceValue[0] == "object") {
  5689. for (var index = 0; index < sourceValue.length; index++) {
  5690. var clonedValue = cloneValue(sourceValue[index], destination);
  5691. if (destination[prop].indexOf(clonedValue) === -1) {
  5692. destination[prop].push(clonedValue);
  5693. }
  5694. }
  5695. }
  5696. else {
  5697. destination[prop] = sourceValue.slice(0);
  5698. }
  5699. }
  5700. }
  5701. else {
  5702. destination[prop] = cloneValue(sourceValue, destination);
  5703. }
  5704. }
  5705. else {
  5706. destination[prop] = sourceValue;
  5707. }
  5708. }
  5709. };
  5710. Tools.IsEmpty = function (obj) {
  5711. for (var i in obj) {
  5712. return false;
  5713. }
  5714. return true;
  5715. };
  5716. Tools.RegisterTopRootEvents = function (events) {
  5717. for (var index = 0; index < events.length; index++) {
  5718. var event = events[index];
  5719. window.addEventListener(event.name, event.handler, false);
  5720. try {
  5721. if (window.parent) {
  5722. window.parent.addEventListener(event.name, event.handler, false);
  5723. }
  5724. }
  5725. catch (e) {
  5726. // Silently fails...
  5727. }
  5728. }
  5729. };
  5730. Tools.UnregisterTopRootEvents = function (events) {
  5731. for (var index = 0; index < events.length; index++) {
  5732. var event = events[index];
  5733. window.removeEventListener(event.name, event.handler);
  5734. try {
  5735. if (window.parent) {
  5736. window.parent.removeEventListener(event.name, event.handler);
  5737. }
  5738. }
  5739. catch (e) {
  5740. // Silently fails...
  5741. }
  5742. }
  5743. };
  5744. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5745. if (mimeType === void 0) { mimeType = "image/png"; }
  5746. // Read the contents of the framebuffer
  5747. var numberOfChannelsByLine = width * 4;
  5748. var halfHeight = height / 2;
  5749. //Reading datas from WebGL
  5750. var data = engine.readPixels(0, 0, width, height);
  5751. //To flip image on Y axis.
  5752. for (var i = 0; i < halfHeight; i++) {
  5753. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5754. var currentCell = j + i * numberOfChannelsByLine;
  5755. var targetLine = height - i - 1;
  5756. var targetCell = j + targetLine * numberOfChannelsByLine;
  5757. var temp = data[currentCell];
  5758. data[currentCell] = data[targetCell];
  5759. data[targetCell] = temp;
  5760. }
  5761. }
  5762. // Create a 2D canvas to store the result
  5763. if (!screenshotCanvas) {
  5764. screenshotCanvas = document.createElement('canvas');
  5765. }
  5766. screenshotCanvas.width = width;
  5767. screenshotCanvas.height = height;
  5768. var context = screenshotCanvas.getContext('2d');
  5769. // Copy the pixels to a 2D canvas
  5770. var imageData = context.createImageData(width, height);
  5771. var castData = (imageData.data);
  5772. castData.set(data);
  5773. context.putImageData(imageData, 0, 0);
  5774. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5775. };
  5776. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5777. if (mimeType === void 0) { mimeType = "image/png"; }
  5778. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5779. if (successCallback) {
  5780. successCallback(base64Image);
  5781. }
  5782. else {
  5783. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5784. if (("download" in document.createElement("a"))) {
  5785. var a = window.document.createElement("a");
  5786. a.href = base64Image;
  5787. var date = new Date();
  5788. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5789. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5790. window.document.body.appendChild(a);
  5791. a.addEventListener("click", function () {
  5792. a.parentElement.removeChild(a);
  5793. });
  5794. a.click();
  5795. //Or opening a new tab with the image if it is not possible to automatically start download.
  5796. }
  5797. else {
  5798. var newWindow = window.open("");
  5799. var img = newWindow.document.createElement("img");
  5800. img.src = base64Image;
  5801. newWindow.document.body.appendChild(img);
  5802. }
  5803. }
  5804. };
  5805. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5806. if (mimeType === void 0) { mimeType = "image/png"; }
  5807. var width;
  5808. var height;
  5809. // If a precision value is specified
  5810. if (size.precision) {
  5811. width = Math.round(engine.getRenderWidth() * size.precision);
  5812. height = Math.round(width / engine.getAspectRatio(camera));
  5813. }
  5814. else if (size.width && size.height) {
  5815. width = size.width;
  5816. height = size.height;
  5817. }
  5818. else if (size.width && !size.height) {
  5819. width = size.width;
  5820. height = Math.round(width / engine.getAspectRatio(camera));
  5821. }
  5822. else if (size.height && !size.width) {
  5823. height = size.height;
  5824. width = Math.round(height * engine.getAspectRatio(camera));
  5825. }
  5826. else if (!isNaN(size)) {
  5827. height = size;
  5828. width = size;
  5829. }
  5830. else {
  5831. Tools.Error("Invalid 'size' parameter !");
  5832. return;
  5833. }
  5834. if (!screenshotCanvas) {
  5835. screenshotCanvas = document.createElement('canvas');
  5836. }
  5837. screenshotCanvas.width = width;
  5838. screenshotCanvas.height = height;
  5839. var renderContext = screenshotCanvas.getContext("2d");
  5840. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5841. var newWidth = width;
  5842. var newHeight = newWidth / ratio;
  5843. if (newHeight > height) {
  5844. newHeight = height;
  5845. newWidth = newHeight * ratio;
  5846. }
  5847. var offsetX = Math.max(0, width - newWidth) / 2;
  5848. var offsetY = Math.max(0, height - newHeight) / 2;
  5849. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5850. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5851. };
  5852. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5853. if (mimeType === void 0) { mimeType = "image/png"; }
  5854. if (samples === void 0) { samples = 1; }
  5855. var width;
  5856. var height;
  5857. //If a precision value is specified
  5858. if (size.precision) {
  5859. width = Math.round(engine.getRenderWidth() * size.precision);
  5860. height = Math.round(width / engine.getAspectRatio(camera));
  5861. size = { width: width, height: height };
  5862. }
  5863. else if (size.width && size.height) {
  5864. width = size.width;
  5865. height = size.height;
  5866. }
  5867. else if (size.width && !size.height) {
  5868. width = size.width;
  5869. height = Math.round(width / engine.getAspectRatio(camera));
  5870. size = { width: width, height: height };
  5871. }
  5872. else if (size.height && !size.width) {
  5873. height = size.height;
  5874. width = Math.round(height * engine.getAspectRatio(camera));
  5875. size = { width: width, height: height };
  5876. }
  5877. else if (!isNaN(size)) {
  5878. height = size;
  5879. width = size;
  5880. }
  5881. else {
  5882. Tools.Error("Invalid 'size' parameter !");
  5883. return;
  5884. }
  5885. var scene = camera.getScene();
  5886. var previousCamera = null;
  5887. if (scene.activeCamera !== camera) {
  5888. previousCamera = scene.activeCamera;
  5889. scene.activeCamera = camera;
  5890. }
  5891. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5892. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5893. texture.renderList = scene.meshes;
  5894. texture.samples = samples;
  5895. texture.onAfterRenderObservable.add(function () {
  5896. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5897. });
  5898. scene.incrementRenderId();
  5899. scene.resetCachedMaterial();
  5900. texture.render(true);
  5901. texture.dispose();
  5902. if (previousCamera) {
  5903. scene.activeCamera = previousCamera;
  5904. }
  5905. camera.getProjectionMatrix(true); // Force cache refresh;
  5906. };
  5907. // XHR response validator for local file scenario
  5908. Tools.ValidateXHRData = function (xhr, dataType) {
  5909. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5910. if (dataType === void 0) { dataType = 7; }
  5911. try {
  5912. if (dataType & 1) {
  5913. if (xhr.responseText && xhr.responseText.length > 0) {
  5914. return true;
  5915. }
  5916. else if (dataType === 1) {
  5917. return false;
  5918. }
  5919. }
  5920. if (dataType & 2) {
  5921. // Check header width and height since there is no "TGA" magic number
  5922. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5923. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5924. return true;
  5925. }
  5926. else if (dataType === 2) {
  5927. return false;
  5928. }
  5929. }
  5930. if (dataType & 4) {
  5931. // Check for the "DDS" magic number
  5932. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5933. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5934. return true;
  5935. }
  5936. else {
  5937. return false;
  5938. }
  5939. }
  5940. }
  5941. catch (e) {
  5942. // Global protection
  5943. }
  5944. return false;
  5945. };
  5946. /**
  5947. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5948. * Be aware Math.random() could cause collisions, but:
  5949. * "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"
  5950. */
  5951. Tools.RandomId = function () {
  5952. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5953. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5954. return v.toString(16);
  5955. });
  5956. };
  5957. Object.defineProperty(Tools, "NoneLogLevel", {
  5958. get: function () {
  5959. return Tools._NoneLogLevel;
  5960. },
  5961. enumerable: true,
  5962. configurable: true
  5963. });
  5964. Object.defineProperty(Tools, "MessageLogLevel", {
  5965. get: function () {
  5966. return Tools._MessageLogLevel;
  5967. },
  5968. enumerable: true,
  5969. configurable: true
  5970. });
  5971. Object.defineProperty(Tools, "WarningLogLevel", {
  5972. get: function () {
  5973. return Tools._WarningLogLevel;
  5974. },
  5975. enumerable: true,
  5976. configurable: true
  5977. });
  5978. Object.defineProperty(Tools, "ErrorLogLevel", {
  5979. get: function () {
  5980. return Tools._ErrorLogLevel;
  5981. },
  5982. enumerable: true,
  5983. configurable: true
  5984. });
  5985. Object.defineProperty(Tools, "AllLogLevel", {
  5986. get: function () {
  5987. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5988. },
  5989. enumerable: true,
  5990. configurable: true
  5991. });
  5992. Tools._AddLogEntry = function (entry) {
  5993. Tools._LogCache = entry + Tools._LogCache;
  5994. if (Tools.OnNewCacheEntry) {
  5995. Tools.OnNewCacheEntry(entry);
  5996. }
  5997. };
  5998. Tools._FormatMessage = function (message) {
  5999. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6000. var date = new Date();
  6001. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6002. };
  6003. Tools._LogDisabled = function (message) {
  6004. // nothing to do
  6005. };
  6006. Tools._LogEnabled = function (message) {
  6007. var formattedMessage = Tools._FormatMessage(message);
  6008. console.log("BJS - " + formattedMessage);
  6009. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6010. Tools._AddLogEntry(entry);
  6011. };
  6012. Tools._WarnDisabled = function (message) {
  6013. // nothing to do
  6014. };
  6015. Tools._WarnEnabled = function (message) {
  6016. var formattedMessage = Tools._FormatMessage(message);
  6017. console.warn("BJS - " + formattedMessage);
  6018. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6019. Tools._AddLogEntry(entry);
  6020. };
  6021. Tools._ErrorDisabled = function (message) {
  6022. // nothing to do
  6023. };
  6024. Tools._ErrorEnabled = function (message) {
  6025. Tools.errorsCount++;
  6026. var formattedMessage = Tools._FormatMessage(message);
  6027. console.error("BJS - " + formattedMessage);
  6028. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6029. Tools._AddLogEntry(entry);
  6030. };
  6031. Object.defineProperty(Tools, "LogCache", {
  6032. get: function () {
  6033. return Tools._LogCache;
  6034. },
  6035. enumerable: true,
  6036. configurable: true
  6037. });
  6038. Tools.ClearLogCache = function () {
  6039. Tools._LogCache = "";
  6040. Tools.errorsCount = 0;
  6041. };
  6042. Object.defineProperty(Tools, "LogLevels", {
  6043. set: function (level) {
  6044. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6045. Tools.Log = Tools._LogEnabled;
  6046. }
  6047. else {
  6048. Tools.Log = Tools._LogDisabled;
  6049. }
  6050. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6051. Tools.Warn = Tools._WarnEnabled;
  6052. }
  6053. else {
  6054. Tools.Warn = Tools._WarnDisabled;
  6055. }
  6056. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6057. Tools.Error = Tools._ErrorEnabled;
  6058. }
  6059. else {
  6060. Tools.Error = Tools._ErrorDisabled;
  6061. }
  6062. },
  6063. enumerable: true,
  6064. configurable: true
  6065. });
  6066. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6067. get: function () {
  6068. return Tools._PerformanceNoneLogLevel;
  6069. },
  6070. enumerable: true,
  6071. configurable: true
  6072. });
  6073. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6074. get: function () {
  6075. return Tools._PerformanceUserMarkLogLevel;
  6076. },
  6077. enumerable: true,
  6078. configurable: true
  6079. });
  6080. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6081. get: function () {
  6082. return Tools._PerformanceConsoleLogLevel;
  6083. },
  6084. enumerable: true,
  6085. configurable: true
  6086. });
  6087. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6088. set: function (level) {
  6089. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6090. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6091. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6092. return;
  6093. }
  6094. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6095. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6096. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6097. return;
  6098. }
  6099. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6100. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6101. },
  6102. enumerable: true,
  6103. configurable: true
  6104. });
  6105. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6106. };
  6107. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6108. };
  6109. Tools._StartUserMark = function (counterName, condition) {
  6110. if (condition === void 0) { condition = true; }
  6111. if (!condition || !Tools._performance.mark) {
  6112. return;
  6113. }
  6114. Tools._performance.mark(counterName + "-Begin");
  6115. };
  6116. Tools._EndUserMark = function (counterName, condition) {
  6117. if (condition === void 0) { condition = true; }
  6118. if (!condition || !Tools._performance.mark) {
  6119. return;
  6120. }
  6121. Tools._performance.mark(counterName + "-End");
  6122. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6123. };
  6124. Tools._StartPerformanceConsole = function (counterName, condition) {
  6125. if (condition === void 0) { condition = true; }
  6126. if (!condition) {
  6127. return;
  6128. }
  6129. Tools._StartUserMark(counterName, condition);
  6130. if (console.time) {
  6131. console.time(counterName);
  6132. }
  6133. };
  6134. Tools._EndPerformanceConsole = function (counterName, condition) {
  6135. if (condition === void 0) { condition = true; }
  6136. if (!condition) {
  6137. return;
  6138. }
  6139. Tools._EndUserMark(counterName, condition);
  6140. if (console.time) {
  6141. console.timeEnd(counterName);
  6142. }
  6143. };
  6144. Object.defineProperty(Tools, "Now", {
  6145. get: function () {
  6146. if (window.performance && window.performance.now) {
  6147. return window.performance.now();
  6148. }
  6149. return new Date().getTime();
  6150. },
  6151. enumerable: true,
  6152. configurable: true
  6153. });
  6154. /**
  6155. * This method will return the name of the class used to create the instance of the given object.
  6156. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6157. * @param object the object to get the class name from
  6158. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6159. */
  6160. Tools.getClassName = function (object, isType) {
  6161. if (isType === void 0) { isType = false; }
  6162. var name = null;
  6163. if (!isType && object.getClassName) {
  6164. name = object.getClassName();
  6165. }
  6166. else {
  6167. if (object instanceof Object) {
  6168. var classObj = isType ? object : Object.getPrototypeOf(object);
  6169. name = classObj.constructor["__bjsclassName__"];
  6170. }
  6171. if (!name) {
  6172. name = typeof object;
  6173. }
  6174. }
  6175. return name;
  6176. };
  6177. Tools.first = function (array, predicate) {
  6178. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6179. var el = array_1[_i];
  6180. if (predicate(el)) {
  6181. return el;
  6182. }
  6183. }
  6184. };
  6185. /**
  6186. * This method will return the name of the full name of the class, including its owning module (if any).
  6187. * 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).
  6188. * @param object the object to get the class name from
  6189. * @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.
  6190. */
  6191. Tools.getFullClassName = function (object, isType) {
  6192. if (isType === void 0) { isType = false; }
  6193. var className = null;
  6194. var moduleName = null;
  6195. if (!isType && object.getClassName) {
  6196. className = object.getClassName();
  6197. }
  6198. else {
  6199. if (object instanceof Object) {
  6200. var classObj = isType ? object : Object.getPrototypeOf(object);
  6201. className = classObj.constructor["__bjsclassName__"];
  6202. moduleName = classObj.constructor["__bjsmoduleName__"];
  6203. }
  6204. if (!className) {
  6205. className = typeof object;
  6206. }
  6207. }
  6208. if (!className) {
  6209. return null;
  6210. }
  6211. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6212. };
  6213. /**
  6214. * 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.
  6215. * @param array
  6216. */
  6217. Tools.arrayOrStringFeeder = function (array) {
  6218. return function (index) {
  6219. if (index >= array.length) {
  6220. return null;
  6221. }
  6222. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6223. if (val && val.getHashCode) {
  6224. val = val.getHashCode();
  6225. }
  6226. if (typeof val === "string") {
  6227. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6228. }
  6229. return val;
  6230. };
  6231. };
  6232. /**
  6233. * Compute the hashCode of a stream of number
  6234. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6235. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6236. * @return the hash code computed
  6237. */
  6238. Tools.hashCodeFromStream = function (feeder) {
  6239. // Based from here: http://stackoverflow.com/a/7616484/802124
  6240. var hash = 0;
  6241. var index = 0;
  6242. var chr = feeder(index++);
  6243. while (chr != null) {
  6244. hash = ((hash << 5) - hash) + chr;
  6245. hash |= 0; // Convert to 32bit integer
  6246. chr = feeder(index++);
  6247. }
  6248. return hash;
  6249. };
  6250. return Tools;
  6251. }());
  6252. Tools.BaseUrl = "";
  6253. Tools.CorsBehavior = "anonymous";
  6254. Tools.UseFallbackTexture = true;
  6255. // Used in case of a texture loading problem
  6256. 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";
  6257. // Logs
  6258. Tools._NoneLogLevel = 0;
  6259. Tools._MessageLogLevel = 1;
  6260. Tools._WarningLogLevel = 2;
  6261. Tools._ErrorLogLevel = 4;
  6262. Tools._LogCache = "";
  6263. Tools.errorsCount = 0;
  6264. Tools.Log = Tools._LogEnabled;
  6265. Tools.Warn = Tools._WarnEnabled;
  6266. Tools.Error = Tools._ErrorEnabled;
  6267. // Performances
  6268. Tools._PerformanceNoneLogLevel = 0;
  6269. Tools._PerformanceUserMarkLogLevel = 1;
  6270. Tools._PerformanceConsoleLogLevel = 2;
  6271. Tools._performance = window.performance;
  6272. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6273. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6274. BABYLON.Tools = Tools;
  6275. /**
  6276. * This class is used to track a performance counter which is number based.
  6277. * The user has access to many properties which give statistics of different nature
  6278. *
  6279. * The implementer can track two kinds of Performance Counter: time and count
  6280. * 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.
  6281. * 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.
  6282. */
  6283. var PerfCounter = (function () {
  6284. function PerfCounter() {
  6285. this._startMonitoringTime = 0;
  6286. this._min = 0;
  6287. this._max = 0;
  6288. this._average = 0;
  6289. this._lastSecAverage = 0;
  6290. this._current = 0;
  6291. this._totalValueCount = 0;
  6292. this._totalAccumulated = 0;
  6293. this._lastSecAccumulated = 0;
  6294. this._lastSecTime = 0;
  6295. this._lastSecValueCount = 0;
  6296. }
  6297. Object.defineProperty(PerfCounter.prototype, "min", {
  6298. /**
  6299. * Returns the smallest value ever
  6300. */
  6301. get: function () {
  6302. return this._min;
  6303. },
  6304. enumerable: true,
  6305. configurable: true
  6306. });
  6307. Object.defineProperty(PerfCounter.prototype, "max", {
  6308. /**
  6309. * Returns the biggest value ever
  6310. */
  6311. get: function () {
  6312. return this._max;
  6313. },
  6314. enumerable: true,
  6315. configurable: true
  6316. });
  6317. Object.defineProperty(PerfCounter.prototype, "average", {
  6318. /**
  6319. * Returns the average value since the performance counter is running
  6320. */
  6321. get: function () {
  6322. return this._average;
  6323. },
  6324. enumerable: true,
  6325. configurable: true
  6326. });
  6327. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6328. /**
  6329. * Returns the average value of the last second the counter was monitored
  6330. */
  6331. get: function () {
  6332. return this._lastSecAverage;
  6333. },
  6334. enumerable: true,
  6335. configurable: true
  6336. });
  6337. Object.defineProperty(PerfCounter.prototype, "current", {
  6338. /**
  6339. * Returns the current value
  6340. */
  6341. get: function () {
  6342. return this._current;
  6343. },
  6344. enumerable: true,
  6345. configurable: true
  6346. });
  6347. Object.defineProperty(PerfCounter.prototype, "total", {
  6348. get: function () {
  6349. return this._totalAccumulated;
  6350. },
  6351. enumerable: true,
  6352. configurable: true
  6353. });
  6354. /**
  6355. * Call this method to start monitoring a new frame.
  6356. * 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.
  6357. */
  6358. PerfCounter.prototype.fetchNewFrame = function () {
  6359. this._totalValueCount++;
  6360. this._current = 0;
  6361. this._lastSecValueCount++;
  6362. };
  6363. /**
  6364. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6365. * @param newCount the count value to add to the monitored count
  6366. * @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.
  6367. */
  6368. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6369. if (!PerfCounter.Enabled) {
  6370. return;
  6371. }
  6372. this._current += newCount;
  6373. if (fetchResult) {
  6374. this._fetchResult();
  6375. }
  6376. };
  6377. /**
  6378. * Start monitoring this performance counter
  6379. */
  6380. PerfCounter.prototype.beginMonitoring = function () {
  6381. if (!PerfCounter.Enabled) {
  6382. return;
  6383. }
  6384. this._startMonitoringTime = Tools.Now;
  6385. };
  6386. /**
  6387. * Compute the time lapsed since the previous beginMonitoring() call.
  6388. * @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
  6389. */
  6390. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6391. if (newFrame === void 0) { newFrame = true; }
  6392. if (!PerfCounter.Enabled) {
  6393. return;
  6394. }
  6395. if (newFrame) {
  6396. this.fetchNewFrame();
  6397. }
  6398. var currentTime = Tools.Now;
  6399. this._current = currentTime - this._startMonitoringTime;
  6400. if (newFrame) {
  6401. this._fetchResult();
  6402. }
  6403. };
  6404. PerfCounter.prototype._fetchResult = function () {
  6405. this._totalAccumulated += this._current;
  6406. this._lastSecAccumulated += this._current;
  6407. // Min/Max update
  6408. this._min = Math.min(this._min, this._current);
  6409. this._max = Math.max(this._max, this._current);
  6410. this._average = this._totalAccumulated / this._totalValueCount;
  6411. // Reset last sec?
  6412. var now = Tools.Now;
  6413. if ((now - this._lastSecTime) > 1000) {
  6414. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6415. this._lastSecTime = now;
  6416. this._lastSecAccumulated = 0;
  6417. this._lastSecValueCount = 0;
  6418. }
  6419. };
  6420. return PerfCounter;
  6421. }());
  6422. PerfCounter.Enabled = true;
  6423. BABYLON.PerfCounter = PerfCounter;
  6424. /**
  6425. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6426. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6427. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6428. * @param name The name of the class, case should be preserved
  6429. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6430. */
  6431. function className(name, module) {
  6432. return function (target) {
  6433. target["__bjsclassName__"] = name;
  6434. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6435. };
  6436. }
  6437. BABYLON.className = className;
  6438. /**
  6439. * An implementation of a loop for asynchronous functions.
  6440. */
  6441. var AsyncLoop = (function () {
  6442. /**
  6443. * Constroctor.
  6444. * @param iterations the number of iterations.
  6445. * @param _fn the function to run each iteration
  6446. * @param _successCallback the callback that will be called upon succesful execution
  6447. * @param offset starting offset.
  6448. */
  6449. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6450. if (offset === void 0) { offset = 0; }
  6451. this.iterations = iterations;
  6452. this._fn = _fn;
  6453. this._successCallback = _successCallback;
  6454. this.index = offset - 1;
  6455. this._done = false;
  6456. }
  6457. /**
  6458. * Execute the next iteration. Must be called after the last iteration was finished.
  6459. */
  6460. AsyncLoop.prototype.executeNext = function () {
  6461. if (!this._done) {
  6462. if (this.index + 1 < this.iterations) {
  6463. ++this.index;
  6464. this._fn(this);
  6465. }
  6466. else {
  6467. this.breakLoop();
  6468. }
  6469. }
  6470. };
  6471. /**
  6472. * Break the loop and run the success callback.
  6473. */
  6474. AsyncLoop.prototype.breakLoop = function () {
  6475. this._done = true;
  6476. this._successCallback();
  6477. };
  6478. /**
  6479. * Helper function
  6480. */
  6481. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6482. if (offset === void 0) { offset = 0; }
  6483. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6484. loop.executeNext();
  6485. return loop;
  6486. };
  6487. /**
  6488. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6489. * @param iterations total number of iterations
  6490. * @param syncedIterations number of synchronous iterations in each async iteration.
  6491. * @param fn the function to call each iteration.
  6492. * @param callback a success call back that will be called when iterating stops.
  6493. * @param breakFunction a break condition (optional)
  6494. * @param timeout timeout settings for the setTimeout function. default - 0.
  6495. * @constructor
  6496. */
  6497. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6498. if (timeout === void 0) { timeout = 0; }
  6499. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6500. if (breakFunction && breakFunction())
  6501. loop.breakLoop();
  6502. else {
  6503. setTimeout(function () {
  6504. for (var i = 0; i < syncedIterations; ++i) {
  6505. var iteration = (loop.index * syncedIterations) + i;
  6506. if (iteration >= iterations)
  6507. break;
  6508. fn(iteration);
  6509. if (breakFunction && breakFunction()) {
  6510. loop.breakLoop();
  6511. break;
  6512. }
  6513. }
  6514. loop.executeNext();
  6515. }, timeout);
  6516. }
  6517. }, callback);
  6518. };
  6519. return AsyncLoop;
  6520. }());
  6521. BABYLON.AsyncLoop = AsyncLoop;
  6522. })(BABYLON || (BABYLON = {}));
  6523. //# sourceMappingURL=babylon.tools.js.map
  6524. var BABYLON;
  6525. (function (BABYLON) {
  6526. var Internals;
  6527. (function (Internals) {
  6528. var _AlphaState = (function () {
  6529. /**
  6530. * Initializes the state.
  6531. */
  6532. function _AlphaState() {
  6533. this._isAlphaBlendDirty = false;
  6534. this._isBlendFunctionParametersDirty = false;
  6535. this._isBlendEquationParametersDirty = false;
  6536. this._isBlendConstantsDirty = false;
  6537. this._alphaBlend = false;
  6538. this._blendFunctionParameters = new Array(4);
  6539. this._blendEquationParameters = new Array(2);
  6540. this._blendConstants = new Array(4);
  6541. this.reset();
  6542. }
  6543. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6544. get: function () {
  6545. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6546. },
  6547. enumerable: true,
  6548. configurable: true
  6549. });
  6550. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6551. get: function () {
  6552. return this._alphaBlend;
  6553. },
  6554. set: function (value) {
  6555. if (this._alphaBlend === value) {
  6556. return;
  6557. }
  6558. this._alphaBlend = value;
  6559. this._isAlphaBlendDirty = true;
  6560. },
  6561. enumerable: true,
  6562. configurable: true
  6563. });
  6564. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6565. if (this._blendConstants[0] === r &&
  6566. this._blendConstants[1] === g &&
  6567. this._blendConstants[2] === b &&
  6568. this._blendConstants[3] === a) {
  6569. return;
  6570. }
  6571. this._blendConstants[0] = r;
  6572. this._blendConstants[1] = g;
  6573. this._blendConstants[2] = b;
  6574. this._blendConstants[3] = a;
  6575. this._isBlendConstantsDirty = true;
  6576. };
  6577. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6578. if (this._blendFunctionParameters[0] === value0 &&
  6579. this._blendFunctionParameters[1] === value1 &&
  6580. this._blendFunctionParameters[2] === value2 &&
  6581. this._blendFunctionParameters[3] === value3) {
  6582. return;
  6583. }
  6584. this._blendFunctionParameters[0] = value0;
  6585. this._blendFunctionParameters[1] = value1;
  6586. this._blendFunctionParameters[2] = value2;
  6587. this._blendFunctionParameters[3] = value3;
  6588. this._isBlendFunctionParametersDirty = true;
  6589. };
  6590. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6591. if (this._blendEquationParameters[0] === rgb &&
  6592. this._blendEquationParameters[1] === alpha) {
  6593. return;
  6594. }
  6595. this._blendEquationParameters[0] = rgb;
  6596. this._blendEquationParameters[1] = alpha;
  6597. this._isBlendEquationParametersDirty = true;
  6598. };
  6599. _AlphaState.prototype.reset = function () {
  6600. this._alphaBlend = false;
  6601. this._blendFunctionParameters[0] = null;
  6602. this._blendFunctionParameters[1] = null;
  6603. this._blendFunctionParameters[2] = null;
  6604. this._blendFunctionParameters[3] = null;
  6605. this._blendEquationParameters[0] = null;
  6606. this._blendEquationParameters[1] = null;
  6607. this._blendConstants[0] = null;
  6608. this._blendConstants[1] = null;
  6609. this._blendConstants[2] = null;
  6610. this._blendConstants[3] = null;
  6611. this._isAlphaBlendDirty = true;
  6612. this._isBlendFunctionParametersDirty = false;
  6613. this._isBlendEquationParametersDirty = false;
  6614. this._isBlendConstantsDirty = false;
  6615. };
  6616. _AlphaState.prototype.apply = function (gl) {
  6617. if (!this.isDirty) {
  6618. return;
  6619. }
  6620. // Alpha blend
  6621. if (this._isAlphaBlendDirty) {
  6622. if (this._alphaBlend) {
  6623. gl.enable(gl.BLEND);
  6624. }
  6625. else {
  6626. gl.disable(gl.BLEND);
  6627. }
  6628. this._isAlphaBlendDirty = false;
  6629. }
  6630. // Alpha function
  6631. if (this._isBlendFunctionParametersDirty) {
  6632. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6633. this._isBlendFunctionParametersDirty = false;
  6634. }
  6635. // Alpha equation
  6636. if (this._isBlendEquationParametersDirty) {
  6637. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6638. this._isBlendEquationParametersDirty = false;
  6639. }
  6640. // Constants
  6641. if (this._isBlendConstantsDirty) {
  6642. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6643. this._isBlendConstantsDirty = false;
  6644. }
  6645. };
  6646. return _AlphaState;
  6647. }());
  6648. Internals._AlphaState = _AlphaState;
  6649. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6650. })(BABYLON || (BABYLON = {}));
  6651. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6652. var BABYLON;
  6653. (function (BABYLON) {
  6654. var Internals;
  6655. (function (Internals) {
  6656. var _DepthCullingState = (function () {
  6657. /**
  6658. * Initializes the state.
  6659. */
  6660. function _DepthCullingState() {
  6661. this._isDepthTestDirty = false;
  6662. this._isDepthMaskDirty = false;
  6663. this._isDepthFuncDirty = false;
  6664. this._isCullFaceDirty = false;
  6665. this._isCullDirty = false;
  6666. this._isZOffsetDirty = false;
  6667. this.reset();
  6668. }
  6669. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6670. get: function () {
  6671. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6672. },
  6673. enumerable: true,
  6674. configurable: true
  6675. });
  6676. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6677. get: function () {
  6678. return this._zOffset;
  6679. },
  6680. set: function (value) {
  6681. if (this._zOffset === value) {
  6682. return;
  6683. }
  6684. this._zOffset = value;
  6685. this._isZOffsetDirty = true;
  6686. },
  6687. enumerable: true,
  6688. configurable: true
  6689. });
  6690. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6691. get: function () {
  6692. return this._cullFace;
  6693. },
  6694. set: function (value) {
  6695. if (this._cullFace === value) {
  6696. return;
  6697. }
  6698. this._cullFace = value;
  6699. this._isCullFaceDirty = true;
  6700. },
  6701. enumerable: true,
  6702. configurable: true
  6703. });
  6704. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6705. get: function () {
  6706. return this._cull;
  6707. },
  6708. set: function (value) {
  6709. if (this._cull === value) {
  6710. return;
  6711. }
  6712. this._cull = value;
  6713. this._isCullDirty = true;
  6714. },
  6715. enumerable: true,
  6716. configurable: true
  6717. });
  6718. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6719. get: function () {
  6720. return this._depthFunc;
  6721. },
  6722. set: function (value) {
  6723. if (this._depthFunc === value) {
  6724. return;
  6725. }
  6726. this._depthFunc = value;
  6727. this._isDepthFuncDirty = true;
  6728. },
  6729. enumerable: true,
  6730. configurable: true
  6731. });
  6732. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6733. get: function () {
  6734. return this._depthMask;
  6735. },
  6736. set: function (value) {
  6737. if (this._depthMask === value) {
  6738. return;
  6739. }
  6740. this._depthMask = value;
  6741. this._isDepthMaskDirty = true;
  6742. },
  6743. enumerable: true,
  6744. configurable: true
  6745. });
  6746. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6747. get: function () {
  6748. return this._depthTest;
  6749. },
  6750. set: function (value) {
  6751. if (this._depthTest === value) {
  6752. return;
  6753. }
  6754. this._depthTest = value;
  6755. this._isDepthTestDirty = true;
  6756. },
  6757. enumerable: true,
  6758. configurable: true
  6759. });
  6760. _DepthCullingState.prototype.reset = function () {
  6761. this._depthMask = true;
  6762. this._depthTest = true;
  6763. this._depthFunc = null;
  6764. this._cullFace = null;
  6765. this._cull = null;
  6766. this._zOffset = 0;
  6767. this._isDepthTestDirty = true;
  6768. this._isDepthMaskDirty = true;
  6769. this._isDepthFuncDirty = false;
  6770. this._isCullFaceDirty = false;
  6771. this._isCullDirty = false;
  6772. this._isZOffsetDirty = false;
  6773. };
  6774. _DepthCullingState.prototype.apply = function (gl) {
  6775. if (!this.isDirty) {
  6776. return;
  6777. }
  6778. // Cull
  6779. if (this._isCullDirty) {
  6780. if (this.cull) {
  6781. gl.enable(gl.CULL_FACE);
  6782. }
  6783. else {
  6784. gl.disable(gl.CULL_FACE);
  6785. }
  6786. this._isCullDirty = false;
  6787. }
  6788. // Cull face
  6789. if (this._isCullFaceDirty) {
  6790. gl.cullFace(this.cullFace);
  6791. this._isCullFaceDirty = false;
  6792. }
  6793. // Depth mask
  6794. if (this._isDepthMaskDirty) {
  6795. gl.depthMask(this.depthMask);
  6796. this._isDepthMaskDirty = false;
  6797. }
  6798. // Depth test
  6799. if (this._isDepthTestDirty) {
  6800. if (this.depthTest) {
  6801. gl.enable(gl.DEPTH_TEST);
  6802. }
  6803. else {
  6804. gl.disable(gl.DEPTH_TEST);
  6805. }
  6806. this._isDepthTestDirty = false;
  6807. }
  6808. // Depth func
  6809. if (this._isDepthFuncDirty) {
  6810. gl.depthFunc(this.depthFunc);
  6811. this._isDepthFuncDirty = false;
  6812. }
  6813. // zOffset
  6814. if (this._isZOffsetDirty) {
  6815. if (this.zOffset) {
  6816. gl.enable(gl.POLYGON_OFFSET_FILL);
  6817. gl.polygonOffset(this.zOffset, 0);
  6818. }
  6819. else {
  6820. gl.disable(gl.POLYGON_OFFSET_FILL);
  6821. }
  6822. this._isZOffsetDirty = false;
  6823. }
  6824. };
  6825. return _DepthCullingState;
  6826. }());
  6827. Internals._DepthCullingState = _DepthCullingState;
  6828. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6829. })(BABYLON || (BABYLON = {}));
  6830. //# sourceMappingURL=babylon.depthCullingState.js.map
  6831. var BABYLON;
  6832. (function (BABYLON) {
  6833. var Internals;
  6834. (function (Internals) {
  6835. var _StencilState = (function () {
  6836. function _StencilState() {
  6837. this._isStencilTestDirty = false;
  6838. this._isStencilMaskDirty = false;
  6839. this._isStencilFuncDirty = false;
  6840. this._isStencilOpDirty = false;
  6841. this.reset();
  6842. }
  6843. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6844. get: function () {
  6845. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6846. },
  6847. enumerable: true,
  6848. configurable: true
  6849. });
  6850. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6851. get: function () {
  6852. return this._stencilFunc;
  6853. },
  6854. set: function (value) {
  6855. if (this._stencilFunc === value) {
  6856. return;
  6857. }
  6858. this._stencilFunc = value;
  6859. this._isStencilFuncDirty = true;
  6860. },
  6861. enumerable: true,
  6862. configurable: true
  6863. });
  6864. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6865. get: function () {
  6866. return this._stencilFuncRef;
  6867. },
  6868. set: function (value) {
  6869. if (this._stencilFuncRef === value) {
  6870. return;
  6871. }
  6872. this._stencilFuncRef = value;
  6873. this._isStencilFuncDirty = true;
  6874. },
  6875. enumerable: true,
  6876. configurable: true
  6877. });
  6878. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6879. get: function () {
  6880. return this._stencilFuncMask;
  6881. },
  6882. set: function (value) {
  6883. if (this._stencilFuncMask === value) {
  6884. return;
  6885. }
  6886. this._stencilFuncMask = value;
  6887. this._isStencilFuncDirty = true;
  6888. },
  6889. enumerable: true,
  6890. configurable: true
  6891. });
  6892. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6893. get: function () {
  6894. return this._stencilOpStencilFail;
  6895. },
  6896. set: function (value) {
  6897. if (this._stencilOpStencilFail === value) {
  6898. return;
  6899. }
  6900. this._stencilOpStencilFail = value;
  6901. this._isStencilOpDirty = true;
  6902. },
  6903. enumerable: true,
  6904. configurable: true
  6905. });
  6906. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6907. get: function () {
  6908. return this._stencilOpDepthFail;
  6909. },
  6910. set: function (value) {
  6911. if (this._stencilOpDepthFail === value) {
  6912. return;
  6913. }
  6914. this._stencilOpDepthFail = value;
  6915. this._isStencilOpDirty = true;
  6916. },
  6917. enumerable: true,
  6918. configurable: true
  6919. });
  6920. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6921. get: function () {
  6922. return this._stencilOpStencilDepthPass;
  6923. },
  6924. set: function (value) {
  6925. if (this._stencilOpStencilDepthPass === value) {
  6926. return;
  6927. }
  6928. this._stencilOpStencilDepthPass = value;
  6929. this._isStencilOpDirty = true;
  6930. },
  6931. enumerable: true,
  6932. configurable: true
  6933. });
  6934. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6935. get: function () {
  6936. return this._stencilMask;
  6937. },
  6938. set: function (value) {
  6939. if (this._stencilMask === value) {
  6940. return;
  6941. }
  6942. this._stencilMask = value;
  6943. this._isStencilMaskDirty = true;
  6944. },
  6945. enumerable: true,
  6946. configurable: true
  6947. });
  6948. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6949. get: function () {
  6950. return this._stencilTest;
  6951. },
  6952. set: function (value) {
  6953. if (this._stencilTest === value) {
  6954. return;
  6955. }
  6956. this._stencilTest = value;
  6957. this._isStencilTestDirty = true;
  6958. },
  6959. enumerable: true,
  6960. configurable: true
  6961. });
  6962. _StencilState.prototype.reset = function () {
  6963. this._stencilTest = false;
  6964. this._stencilMask = 0xFF;
  6965. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6966. this._stencilFuncRef = 1;
  6967. this._stencilFuncMask = 0xFF;
  6968. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6969. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6970. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6971. this._isStencilTestDirty = true;
  6972. this._isStencilMaskDirty = true;
  6973. this._isStencilFuncDirty = true;
  6974. this._isStencilOpDirty = true;
  6975. };
  6976. _StencilState.prototype.apply = function (gl) {
  6977. if (!this.isDirty) {
  6978. return;
  6979. }
  6980. // Stencil test
  6981. if (this._isStencilTestDirty) {
  6982. if (this.stencilTest) {
  6983. gl.enable(gl.STENCIL_TEST);
  6984. }
  6985. else {
  6986. gl.disable(gl.STENCIL_TEST);
  6987. }
  6988. this._isStencilTestDirty = false;
  6989. }
  6990. // Stencil mask
  6991. if (this._isStencilMaskDirty) {
  6992. gl.stencilMask(this.stencilMask);
  6993. this._isStencilMaskDirty = false;
  6994. }
  6995. // Stencil func
  6996. if (this._isStencilFuncDirty) {
  6997. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6998. this._isStencilFuncDirty = false;
  6999. }
  7000. // Stencil op
  7001. if (this._isStencilOpDirty) {
  7002. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7003. this._isStencilOpDirty = false;
  7004. }
  7005. };
  7006. return _StencilState;
  7007. }());
  7008. Internals._StencilState = _StencilState;
  7009. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7010. })(BABYLON || (BABYLON = {}));
  7011. //# sourceMappingURL=babylon.stencilState.js.map
  7012. var BABYLON;
  7013. (function (BABYLON) {
  7014. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7015. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7016. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7017. gl.compileShader(shader);
  7018. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7019. throw new Error(gl.getShaderInfoLog(shader));
  7020. }
  7021. return shader;
  7022. };
  7023. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7024. var magFilter = gl.NEAREST;
  7025. var minFilter = gl.NEAREST;
  7026. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7027. magFilter = gl.LINEAR;
  7028. if (generateMipMaps) {
  7029. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7030. }
  7031. else {
  7032. minFilter = gl.LINEAR;
  7033. }
  7034. }
  7035. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7036. magFilter = gl.LINEAR;
  7037. if (generateMipMaps) {
  7038. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7039. }
  7040. else {
  7041. minFilter = gl.LINEAR;
  7042. }
  7043. }
  7044. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7045. magFilter = gl.NEAREST;
  7046. if (generateMipMaps) {
  7047. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7048. }
  7049. else {
  7050. minFilter = gl.NEAREST;
  7051. }
  7052. }
  7053. return {
  7054. min: minFilter,
  7055. mag: magFilter
  7056. };
  7057. };
  7058. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7059. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7060. var engine = scene.getEngine();
  7061. if (!engine) {
  7062. return;
  7063. }
  7064. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7065. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7066. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7067. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7068. texture._baseWidth = width;
  7069. texture._baseHeight = height;
  7070. texture._width = potWidth;
  7071. texture._height = potHeight;
  7072. texture.isReady = true;
  7073. processFunction(potWidth, potHeight);
  7074. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7077. if (!noMipmap && !isCompressed) {
  7078. gl.generateMipmap(gl.TEXTURE_2D);
  7079. }
  7080. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7081. engine.resetTextureCache();
  7082. scene._removePendingData(texture);
  7083. texture.onLoadedCallbacks.forEach(function (callback) {
  7084. callback();
  7085. });
  7086. texture.onLoadedCallbacks = [];
  7087. };
  7088. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7089. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7090. var img;
  7091. var onload = function () {
  7092. loadedImages[index] = img;
  7093. loadedImages._internalCount++;
  7094. scene._removePendingData(img);
  7095. if (loadedImages._internalCount === 6) {
  7096. onfinish(loadedImages);
  7097. }
  7098. };
  7099. var onerror = function () {
  7100. scene._removePendingData(img);
  7101. if (onErrorCallBack) {
  7102. onErrorCallBack();
  7103. }
  7104. };
  7105. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7106. scene._addPendingData(img);
  7107. };
  7108. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7109. if (onError === void 0) { onError = null; }
  7110. var loadedImages = [];
  7111. loadedImages._internalCount = 0;
  7112. for (var index = 0; index < 6; index++) {
  7113. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7114. }
  7115. };
  7116. var InstancingAttributeInfo = (function () {
  7117. function InstancingAttributeInfo() {
  7118. }
  7119. return InstancingAttributeInfo;
  7120. }());
  7121. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7122. var EngineCapabilities = (function () {
  7123. function EngineCapabilities() {
  7124. }
  7125. return EngineCapabilities;
  7126. }());
  7127. BABYLON.EngineCapabilities = EngineCapabilities;
  7128. /**
  7129. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7130. */
  7131. var Engine = (function () {
  7132. /**
  7133. * @constructor
  7134. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7135. * @param {boolean} [antialias] - enable antialias
  7136. * @param options - further options to be sent to the getContext function
  7137. */
  7138. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7139. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7140. var _this = this;
  7141. // Public members
  7142. this.isFullscreen = false;
  7143. this.isPointerLock = false;
  7144. this.cullBackFaces = true;
  7145. this.renderEvenInBackground = true;
  7146. this.preventCacheWipeBetweenFrames = false;
  7147. // To enable/disable IDB support and avoid XHR on .manifest
  7148. this.enableOfflineSupport = BABYLON.Database;
  7149. this.scenes = new Array();
  7150. // Observables
  7151. /**
  7152. * Observable event triggered each time the rendering canvas is resized
  7153. */
  7154. this.onResizeObservable = new BABYLON.Observable();
  7155. /**
  7156. * Observable event triggered each time the canvas lost focus
  7157. */
  7158. this.onCanvasBlurObservable = new BABYLON.Observable();
  7159. this._windowIsBackground = false;
  7160. this._webGLVersion = 1.0;
  7161. this._badOS = false;
  7162. this._drawCalls = new BABYLON.PerfCounter();
  7163. this._renderingQueueLaunched = false;
  7164. this._activeRenderLoops = [];
  7165. // FPS
  7166. this.fpsRange = 60;
  7167. this.previousFramesDuration = [];
  7168. this.fps = 60;
  7169. this.deltaTime = 0;
  7170. // States
  7171. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7172. this._stencilState = new BABYLON.Internals._StencilState();
  7173. this._alphaState = new BABYLON.Internals._AlphaState();
  7174. this._alphaMode = Engine.ALPHA_DISABLE;
  7175. // Cache
  7176. this._loadedTexturesCache = new Array();
  7177. this._maxTextureChannels = 16;
  7178. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7179. this._compiledEffects = {};
  7180. this._vertexAttribArraysEnabled = [];
  7181. this._uintIndicesCurrentlySet = false;
  7182. this._currentBoundBuffer = new Array();
  7183. this._currentBufferPointers = [];
  7184. this._currentInstanceLocations = new Array();
  7185. this._currentInstanceBuffers = new Array();
  7186. this._vaoRecordInProgress = false;
  7187. this._mustWipeVertexAttributes = false;
  7188. // Hardware supported Compressed Textures
  7189. this._texturesSupported = new Array();
  7190. this._onVRFullScreenTriggered = function () {
  7191. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7192. //get the old size before we change
  7193. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7194. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7195. //get the width and height, change the render size
  7196. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7197. var width, height;
  7198. _this.setHardwareScalingLevel(1);
  7199. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7200. }
  7201. else {
  7202. //When the specs are implemented, need to uncomment this.
  7203. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7204. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7205. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7206. _this._vrDisplayEnabled = undefined;
  7207. }
  7208. };
  7209. this._renderingCanvas = canvas;
  7210. Engine.Instances.push(this);
  7211. options = options || {};
  7212. if (antialias != null) {
  7213. options.antialias = antialias;
  7214. }
  7215. if (options.preserveDrawingBuffer === undefined) {
  7216. options.preserveDrawingBuffer = false;
  7217. }
  7218. if (options.audioEngine === undefined) {
  7219. options.audioEngine = true;
  7220. }
  7221. if (options.stencil === undefined) {
  7222. options.stencil = true;
  7223. }
  7224. // GL
  7225. if (!options.disableWebGL2Support) {
  7226. try {
  7227. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7228. if (this._gl) {
  7229. this._webGLVersion = 2.0;
  7230. }
  7231. }
  7232. catch (e) {
  7233. // Do nothing
  7234. }
  7235. }
  7236. if (!this._gl) {
  7237. if (!canvas) {
  7238. throw new Error("The provided canvas is null or undefined.");
  7239. }
  7240. try {
  7241. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7242. }
  7243. catch (e) {
  7244. throw new Error("WebGL not supported");
  7245. }
  7246. }
  7247. if (!this._gl) {
  7248. throw new Error("WebGL not supported");
  7249. }
  7250. this._onBlur = function () {
  7251. _this._windowIsBackground = true;
  7252. };
  7253. this._onFocus = function () {
  7254. _this._windowIsBackground = false;
  7255. };
  7256. this._onCanvasBlur = function () {
  7257. _this.onCanvasBlurObservable.notifyObservers(_this);
  7258. };
  7259. window.addEventListener("blur", this._onBlur);
  7260. window.addEventListener("focus", this._onFocus);
  7261. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7262. // Viewport
  7263. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7264. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7265. this.resize();
  7266. // Caps
  7267. this._isStencilEnable = options.stencil;
  7268. this._caps = new EngineCapabilities();
  7269. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7270. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7271. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7272. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7273. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7274. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7275. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7276. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7277. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7278. // Infos
  7279. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7280. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7281. if (rendererInfo != null) {
  7282. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7283. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7284. }
  7285. if (!this._glVendor) {
  7286. this._glVendor = "Unknown vendor";
  7287. }
  7288. if (!this._glRenderer) {
  7289. this._glRenderer = "Unknown renderer";
  7290. }
  7291. // Extensions
  7292. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7293. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7294. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7295. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7296. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7297. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7298. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7299. 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');
  7300. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7301. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7302. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7303. this._caps.highPrecisionShaderSupported = true;
  7304. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7305. // Checks if some of the format renders first to allow the use of webgl inspector.
  7306. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7307. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7308. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7309. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7310. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7311. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7312. if (this._webGLVersion > 1) {
  7313. Engine.HALF_FLOAT_OES = 0x140B;
  7314. }
  7315. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7316. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7317. // Vertex array object
  7318. if (this._webGLVersion > 1) {
  7319. this._caps.vertexArrayObject = true;
  7320. }
  7321. else {
  7322. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7323. if (vertexArrayObjectExtension != null) {
  7324. this._caps.vertexArrayObject = true;
  7325. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7326. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7327. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7328. }
  7329. else {
  7330. this._caps.vertexArrayObject = false;
  7331. }
  7332. }
  7333. // Instances count
  7334. if (this._webGLVersion > 1) {
  7335. this._caps.instancedArrays = true;
  7336. }
  7337. else {
  7338. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7339. if (instanceExtension != null) {
  7340. this._caps.instancedArrays = true;
  7341. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7342. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7343. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7344. }
  7345. else {
  7346. this._caps.instancedArrays = false;
  7347. }
  7348. }
  7349. // Intelligently add supported compressed formats in order to check for.
  7350. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7351. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7352. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7353. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7354. if (this._caps.astc)
  7355. this.texturesSupported.push('-astc.ktx');
  7356. if (this._caps.s3tc)
  7357. this.texturesSupported.push('-dxt.ktx');
  7358. if (this._caps.pvrtc)
  7359. this.texturesSupported.push('-pvrtc.ktx');
  7360. if (this._caps.etc2)
  7361. this.texturesSupported.push('-etc2.ktx');
  7362. if (this._caps.etc1)
  7363. this.texturesSupported.push('-etc1.ktx');
  7364. if (this._gl.getShaderPrecisionFormat) {
  7365. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7366. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7367. }
  7368. // Depth buffer
  7369. this.setDepthBuffer(true);
  7370. this.setDepthFunctionToLessOrEqual();
  7371. this.setDepthWrite(true);
  7372. // Fullscreen
  7373. this._onFullscreenChange = function () {
  7374. if (document.fullscreen !== undefined) {
  7375. _this.isFullscreen = document.fullscreen;
  7376. }
  7377. else if (document.mozFullScreen !== undefined) {
  7378. _this.isFullscreen = document.mozFullScreen;
  7379. }
  7380. else if (document.webkitIsFullScreen !== undefined) {
  7381. _this.isFullscreen = document.webkitIsFullScreen;
  7382. }
  7383. else if (document.msIsFullScreen !== undefined) {
  7384. _this.isFullscreen = document.msIsFullScreen;
  7385. }
  7386. // Pointer lock
  7387. if (_this.isFullscreen && _this._pointerLockRequested) {
  7388. canvas.requestPointerLock = canvas.requestPointerLock ||
  7389. canvas.msRequestPointerLock ||
  7390. canvas.mozRequestPointerLock ||
  7391. canvas.webkitRequestPointerLock;
  7392. if (canvas.requestPointerLock) {
  7393. canvas.requestPointerLock();
  7394. }
  7395. }
  7396. };
  7397. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7398. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7399. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7400. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7401. // Pointer lock
  7402. this._onPointerLockChange = function () {
  7403. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7404. document.webkitPointerLockElement === canvas ||
  7405. document.msPointerLockElement === canvas ||
  7406. document.pointerLockElement === canvas);
  7407. };
  7408. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7409. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7410. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7411. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7412. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7413. Engine.audioEngine = new BABYLON.AudioEngine();
  7414. }
  7415. //Load WebVR Devices
  7416. if (options.autoEnableWebVR) {
  7417. this.initWebVR();
  7418. }
  7419. //Detect if we are running on a faulty buggy OS.
  7420. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7421. //ua sniffing is the tool of the devil.
  7422. this._badOS = regexp.test(navigator.userAgent);
  7423. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7424. }
  7425. Object.defineProperty(Engine, "LastCreatedEngine", {
  7426. get: function () {
  7427. if (Engine.Instances.length === 0) {
  7428. return null;
  7429. }
  7430. return Engine.Instances[Engine.Instances.length - 1];
  7431. },
  7432. enumerable: true,
  7433. configurable: true
  7434. });
  7435. Object.defineProperty(Engine, "LastCreatedScene", {
  7436. get: function () {
  7437. var lastCreatedEngine = Engine.LastCreatedEngine;
  7438. if (!lastCreatedEngine) {
  7439. return null;
  7440. }
  7441. if (lastCreatedEngine.scenes.length === 0) {
  7442. return null;
  7443. }
  7444. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7445. },
  7446. enumerable: true,
  7447. configurable: true
  7448. });
  7449. /**
  7450. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7451. */
  7452. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7453. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7454. var engine = Engine.Instances[engineIndex];
  7455. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7456. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7457. }
  7458. }
  7459. };
  7460. Object.defineProperty(Engine, "NEVER", {
  7461. get: function () {
  7462. return Engine._NEVER;
  7463. },
  7464. enumerable: true,
  7465. configurable: true
  7466. });
  7467. Object.defineProperty(Engine, "ALWAYS", {
  7468. get: function () {
  7469. return Engine._ALWAYS;
  7470. },
  7471. enumerable: true,
  7472. configurable: true
  7473. });
  7474. Object.defineProperty(Engine, "LESS", {
  7475. get: function () {
  7476. return Engine._LESS;
  7477. },
  7478. enumerable: true,
  7479. configurable: true
  7480. });
  7481. Object.defineProperty(Engine, "EQUAL", {
  7482. get: function () {
  7483. return Engine._EQUAL;
  7484. },
  7485. enumerable: true,
  7486. configurable: true
  7487. });
  7488. Object.defineProperty(Engine, "LEQUAL", {
  7489. get: function () {
  7490. return Engine._LEQUAL;
  7491. },
  7492. enumerable: true,
  7493. configurable: true
  7494. });
  7495. Object.defineProperty(Engine, "GREATER", {
  7496. get: function () {
  7497. return Engine._GREATER;
  7498. },
  7499. enumerable: true,
  7500. configurable: true
  7501. });
  7502. Object.defineProperty(Engine, "GEQUAL", {
  7503. get: function () {
  7504. return Engine._GEQUAL;
  7505. },
  7506. enumerable: true,
  7507. configurable: true
  7508. });
  7509. Object.defineProperty(Engine, "NOTEQUAL", {
  7510. get: function () {
  7511. return Engine._NOTEQUAL;
  7512. },
  7513. enumerable: true,
  7514. configurable: true
  7515. });
  7516. Object.defineProperty(Engine, "KEEP", {
  7517. get: function () {
  7518. return Engine._KEEP;
  7519. },
  7520. enumerable: true,
  7521. configurable: true
  7522. });
  7523. Object.defineProperty(Engine, "REPLACE", {
  7524. get: function () {
  7525. return Engine._REPLACE;
  7526. },
  7527. enumerable: true,
  7528. configurable: true
  7529. });
  7530. Object.defineProperty(Engine, "INCR", {
  7531. get: function () {
  7532. return Engine._INCR;
  7533. },
  7534. enumerable: true,
  7535. configurable: true
  7536. });
  7537. Object.defineProperty(Engine, "DECR", {
  7538. get: function () {
  7539. return Engine._DECR;
  7540. },
  7541. enumerable: true,
  7542. configurable: true
  7543. });
  7544. Object.defineProperty(Engine, "INVERT", {
  7545. get: function () {
  7546. return Engine._INVERT;
  7547. },
  7548. enumerable: true,
  7549. configurable: true
  7550. });
  7551. Object.defineProperty(Engine, "INCR_WRAP", {
  7552. get: function () {
  7553. return Engine._INCR_WRAP;
  7554. },
  7555. enumerable: true,
  7556. configurable: true
  7557. });
  7558. Object.defineProperty(Engine, "DECR_WRAP", {
  7559. get: function () {
  7560. return Engine._DECR_WRAP;
  7561. },
  7562. enumerable: true,
  7563. configurable: true
  7564. });
  7565. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7566. get: function () {
  7567. return Engine._ALPHA_DISABLE;
  7568. },
  7569. enumerable: true,
  7570. configurable: true
  7571. });
  7572. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7573. get: function () {
  7574. return Engine._ALPHA_ONEONE;
  7575. },
  7576. enumerable: true,
  7577. configurable: true
  7578. });
  7579. Object.defineProperty(Engine, "ALPHA_ADD", {
  7580. get: function () {
  7581. return Engine._ALPHA_ADD;
  7582. },
  7583. enumerable: true,
  7584. configurable: true
  7585. });
  7586. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7587. get: function () {
  7588. return Engine._ALPHA_COMBINE;
  7589. },
  7590. enumerable: true,
  7591. configurable: true
  7592. });
  7593. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7594. get: function () {
  7595. return Engine._ALPHA_SUBTRACT;
  7596. },
  7597. enumerable: true,
  7598. configurable: true
  7599. });
  7600. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7601. get: function () {
  7602. return Engine._ALPHA_MULTIPLY;
  7603. },
  7604. enumerable: true,
  7605. configurable: true
  7606. });
  7607. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7608. get: function () {
  7609. return Engine._ALPHA_MAXIMIZED;
  7610. },
  7611. enumerable: true,
  7612. configurable: true
  7613. });
  7614. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7615. get: function () {
  7616. return Engine._ALPHA_PREMULTIPLIED;
  7617. },
  7618. enumerable: true,
  7619. configurable: true
  7620. });
  7621. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7622. get: function () {
  7623. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7624. },
  7625. enumerable: true,
  7626. configurable: true
  7627. });
  7628. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7629. get: function () {
  7630. return Engine._ALPHA_INTERPOLATE;
  7631. },
  7632. enumerable: true,
  7633. configurable: true
  7634. });
  7635. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7636. get: function () {
  7637. return Engine._ALPHA_SCREENMODE;
  7638. },
  7639. enumerable: true,
  7640. configurable: true
  7641. });
  7642. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7643. get: function () {
  7644. return Engine._DELAYLOADSTATE_NONE;
  7645. },
  7646. enumerable: true,
  7647. configurable: true
  7648. });
  7649. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7650. get: function () {
  7651. return Engine._DELAYLOADSTATE_LOADED;
  7652. },
  7653. enumerable: true,
  7654. configurable: true
  7655. });
  7656. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7657. get: function () {
  7658. return Engine._DELAYLOADSTATE_LOADING;
  7659. },
  7660. enumerable: true,
  7661. configurable: true
  7662. });
  7663. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7664. get: function () {
  7665. return Engine._DELAYLOADSTATE_NOTLOADED;
  7666. },
  7667. enumerable: true,
  7668. configurable: true
  7669. });
  7670. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7671. get: function () {
  7672. return Engine._TEXTUREFORMAT_ALPHA;
  7673. },
  7674. enumerable: true,
  7675. configurable: true
  7676. });
  7677. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7678. get: function () {
  7679. return Engine._TEXTUREFORMAT_LUMINANCE;
  7680. },
  7681. enumerable: true,
  7682. configurable: true
  7683. });
  7684. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7685. get: function () {
  7686. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7687. },
  7688. enumerable: true,
  7689. configurable: true
  7690. });
  7691. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7692. get: function () {
  7693. return Engine._TEXTUREFORMAT_RGB;
  7694. },
  7695. enumerable: true,
  7696. configurable: true
  7697. });
  7698. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7699. get: function () {
  7700. return Engine._TEXTUREFORMAT_RGBA;
  7701. },
  7702. enumerable: true,
  7703. configurable: true
  7704. });
  7705. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7706. get: function () {
  7707. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7708. },
  7709. enumerable: true,
  7710. configurable: true
  7711. });
  7712. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7713. get: function () {
  7714. return Engine._TEXTURETYPE_FLOAT;
  7715. },
  7716. enumerable: true,
  7717. configurable: true
  7718. });
  7719. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7720. get: function () {
  7721. return Engine._TEXTURETYPE_HALF_FLOAT;
  7722. },
  7723. enumerable: true,
  7724. configurable: true
  7725. });
  7726. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7727. get: function () {
  7728. return Engine._SCALEMODE_FLOOR;
  7729. },
  7730. enumerable: true,
  7731. configurable: true
  7732. });
  7733. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7734. get: function () {
  7735. return Engine._SCALEMODE_NEAREST;
  7736. },
  7737. enumerable: true,
  7738. configurable: true
  7739. });
  7740. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7741. get: function () {
  7742. return Engine._SCALEMODE_CEILING;
  7743. },
  7744. enumerable: true,
  7745. configurable: true
  7746. });
  7747. Object.defineProperty(Engine, "Version", {
  7748. get: function () {
  7749. return "3.0-beta";
  7750. },
  7751. enumerable: true,
  7752. configurable: true
  7753. });
  7754. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7755. get: function () {
  7756. return this._texturesSupported;
  7757. },
  7758. enumerable: true,
  7759. configurable: true
  7760. });
  7761. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7762. get: function () {
  7763. return this._textureFormatInUse;
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7769. // Empty texture
  7770. get: function () {
  7771. if (!this._emptyTexture) {
  7772. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7773. }
  7774. return this._emptyTexture;
  7775. },
  7776. enumerable: true,
  7777. configurable: true
  7778. });
  7779. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7780. get: function () {
  7781. if (!this._emptyCubeTexture) {
  7782. var faceData = new Uint8Array(4);
  7783. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7784. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7785. }
  7786. return this._emptyCubeTexture;
  7787. },
  7788. enumerable: true,
  7789. configurable: true
  7790. });
  7791. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7792. get: function () {
  7793. return this._webGLVersion;
  7794. },
  7795. enumerable: true,
  7796. configurable: true
  7797. });
  7798. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7799. /**
  7800. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7801. */
  7802. get: function () {
  7803. return this._isStencilEnable;
  7804. },
  7805. enumerable: true,
  7806. configurable: true
  7807. });
  7808. Engine.prototype._prepareWorkingCanvas = function () {
  7809. if (this._workingCanvas) {
  7810. return;
  7811. }
  7812. this._workingCanvas = document.createElement("canvas");
  7813. this._workingContext = this._workingCanvas.getContext("2d");
  7814. };
  7815. Engine.prototype.resetTextureCache = function () {
  7816. for (var index = 0; index < this._maxTextureChannels; index++) {
  7817. this._activeTexturesCache[index] = null;
  7818. }
  7819. };
  7820. Engine.prototype.getGlInfo = function () {
  7821. return {
  7822. vendor: this._glVendor,
  7823. renderer: this._glRenderer,
  7824. version: this._glVersion
  7825. };
  7826. };
  7827. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7828. if (useScreen === void 0) { useScreen = false; }
  7829. var viewport = camera.viewport;
  7830. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7831. };
  7832. Engine.prototype.getRenderWidth = function (useScreen) {
  7833. if (useScreen === void 0) { useScreen = false; }
  7834. if (!useScreen && this._currentRenderTarget) {
  7835. return this._currentRenderTarget._width;
  7836. }
  7837. return this._renderingCanvas.width;
  7838. };
  7839. Engine.prototype.getRenderHeight = function (useScreen) {
  7840. if (useScreen === void 0) { useScreen = false; }
  7841. if (!useScreen && this._currentRenderTarget) {
  7842. return this._currentRenderTarget._height;
  7843. }
  7844. return this._renderingCanvas.height;
  7845. };
  7846. Engine.prototype.getRenderingCanvas = function () {
  7847. return this._renderingCanvas;
  7848. };
  7849. Engine.prototype.getRenderingCanvasClientRect = function () {
  7850. return this._renderingCanvas.getBoundingClientRect();
  7851. };
  7852. Engine.prototype.setHardwareScalingLevel = function (level) {
  7853. this._hardwareScalingLevel = level;
  7854. this.resize();
  7855. };
  7856. Engine.prototype.getHardwareScalingLevel = function () {
  7857. return this._hardwareScalingLevel;
  7858. };
  7859. Engine.prototype.getLoadedTexturesCache = function () {
  7860. return this._loadedTexturesCache;
  7861. };
  7862. Engine.prototype.getCaps = function () {
  7863. return this._caps;
  7864. };
  7865. Object.defineProperty(Engine.prototype, "drawCalls", {
  7866. get: function () {
  7867. return this._drawCalls.current;
  7868. },
  7869. enumerable: true,
  7870. configurable: true
  7871. });
  7872. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7873. get: function () {
  7874. return this._drawCalls;
  7875. },
  7876. enumerable: true,
  7877. configurable: true
  7878. });
  7879. Engine.prototype.getDepthFunction = function () {
  7880. return this._depthCullingState.depthFunc;
  7881. };
  7882. Engine.prototype.setDepthFunction = function (depthFunc) {
  7883. this._depthCullingState.depthFunc = depthFunc;
  7884. };
  7885. Engine.prototype.setDepthFunctionToGreater = function () {
  7886. this._depthCullingState.depthFunc = this._gl.GREATER;
  7887. };
  7888. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7889. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7890. };
  7891. Engine.prototype.setDepthFunctionToLess = function () {
  7892. this._depthCullingState.depthFunc = this._gl.LESS;
  7893. };
  7894. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7895. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7896. };
  7897. Engine.prototype.getStencilBuffer = function () {
  7898. return this._stencilState.stencilTest;
  7899. };
  7900. Engine.prototype.setStencilBuffer = function (enable) {
  7901. this._stencilState.stencilTest = enable;
  7902. };
  7903. Engine.prototype.getStencilMask = function () {
  7904. return this._stencilState.stencilMask;
  7905. };
  7906. Engine.prototype.setStencilMask = function (mask) {
  7907. this._stencilState.stencilMask = mask;
  7908. };
  7909. Engine.prototype.getStencilFunction = function () {
  7910. return this._stencilState.stencilFunc;
  7911. };
  7912. Engine.prototype.getStencilFunctionReference = function () {
  7913. return this._stencilState.stencilFuncRef;
  7914. };
  7915. Engine.prototype.getStencilFunctionMask = function () {
  7916. return this._stencilState.stencilFuncMask;
  7917. };
  7918. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7919. this._stencilState.stencilFunc = stencilFunc;
  7920. };
  7921. Engine.prototype.setStencilFunctionReference = function (reference) {
  7922. this._stencilState.stencilFuncRef = reference;
  7923. };
  7924. Engine.prototype.setStencilFunctionMask = function (mask) {
  7925. this._stencilState.stencilFuncMask = mask;
  7926. };
  7927. Engine.prototype.getStencilOperationFail = function () {
  7928. return this._stencilState.stencilOpStencilFail;
  7929. };
  7930. Engine.prototype.getStencilOperationDepthFail = function () {
  7931. return this._stencilState.stencilOpDepthFail;
  7932. };
  7933. Engine.prototype.getStencilOperationPass = function () {
  7934. return this._stencilState.stencilOpStencilDepthPass;
  7935. };
  7936. Engine.prototype.setStencilOperationFail = function (operation) {
  7937. this._stencilState.stencilOpStencilFail = operation;
  7938. };
  7939. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7940. this._stencilState.stencilOpDepthFail = operation;
  7941. };
  7942. Engine.prototype.setStencilOperationPass = function (operation) {
  7943. this._stencilState.stencilOpStencilDepthPass = operation;
  7944. };
  7945. Engine.prototype.setDitheringState = function (value) {
  7946. if (value) {
  7947. this._gl.enable(this._gl.DITHER);
  7948. }
  7949. else {
  7950. this._gl.disable(this._gl.DITHER);
  7951. }
  7952. };
  7953. /**
  7954. * stop executing a render loop function and remove it from the execution array
  7955. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7956. */
  7957. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7958. if (!renderFunction) {
  7959. this._activeRenderLoops = [];
  7960. return;
  7961. }
  7962. var index = this._activeRenderLoops.indexOf(renderFunction);
  7963. if (index >= 0) {
  7964. this._activeRenderLoops.splice(index, 1);
  7965. }
  7966. };
  7967. Engine.prototype._renderLoop = function () {
  7968. var shouldRender = true;
  7969. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7970. shouldRender = false;
  7971. }
  7972. if (shouldRender) {
  7973. // Start new frame
  7974. this.beginFrame();
  7975. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7976. var renderFunction = this._activeRenderLoops[index];
  7977. renderFunction();
  7978. }
  7979. // Present
  7980. this.endFrame();
  7981. }
  7982. if (this._activeRenderLoops.length > 0) {
  7983. // Register new frame
  7984. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7985. }
  7986. else {
  7987. this._renderingQueueLaunched = false;
  7988. }
  7989. };
  7990. /**
  7991. * Register and execute a render loop. The engine can have more than one render function.
  7992. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7993. * @example
  7994. * engine.runRenderLoop(function () {
  7995. * scene.render()
  7996. * })
  7997. */
  7998. Engine.prototype.runRenderLoop = function (renderFunction) {
  7999. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8000. return;
  8001. }
  8002. this._activeRenderLoops.push(renderFunction);
  8003. if (!this._renderingQueueLaunched) {
  8004. this._renderingQueueLaunched = true;
  8005. this._bindedRenderFunction = this._renderLoop.bind(this);
  8006. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8007. }
  8008. };
  8009. /**
  8010. * Toggle full screen mode.
  8011. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8012. * @param {any} options - an options object to be sent to the requestFullscreen function
  8013. */
  8014. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8015. if (this.isFullscreen) {
  8016. BABYLON.Tools.ExitFullscreen();
  8017. }
  8018. else {
  8019. this._pointerLockRequested = requestPointerLock;
  8020. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8021. }
  8022. };
  8023. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8024. if (stencil === void 0) { stencil = false; }
  8025. this.applyStates();
  8026. var mode = 0;
  8027. if (backBuffer && color) {
  8028. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8029. mode |= this._gl.COLOR_BUFFER_BIT;
  8030. }
  8031. if (depth) {
  8032. this._gl.clearDepth(1.0);
  8033. mode |= this._gl.DEPTH_BUFFER_BIT;
  8034. }
  8035. if (stencil) {
  8036. this._gl.clearStencil(0);
  8037. mode |= this._gl.STENCIL_BUFFER_BIT;
  8038. }
  8039. this._gl.clear(mode);
  8040. };
  8041. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8042. var gl = this._gl;
  8043. // Save state
  8044. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8045. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8046. // Change state
  8047. gl.enable(gl.SCISSOR_TEST);
  8048. gl.scissor(x, y, width, height);
  8049. // Clear
  8050. this.clear(clearColor, true, true, true);
  8051. // Restore state
  8052. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8053. if (curScissor === true) {
  8054. gl.enable(gl.SCISSOR_TEST);
  8055. }
  8056. else {
  8057. gl.disable(gl.SCISSOR_TEST);
  8058. }
  8059. };
  8060. /**
  8061. * Set the WebGL's viewport
  8062. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8063. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8064. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8065. */
  8066. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8067. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8068. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8069. var x = viewport.x || 0;
  8070. var y = viewport.y || 0;
  8071. this._cachedViewport = viewport;
  8072. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8073. };
  8074. /**
  8075. * Directly set the WebGL Viewport
  8076. * The x, y, width & height are directly passed to the WebGL call
  8077. * @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.
  8078. */
  8079. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8080. var currentViewport = this._cachedViewport;
  8081. this._cachedViewport = null;
  8082. this._gl.viewport(x, y, width, height);
  8083. return currentViewport;
  8084. };
  8085. Engine.prototype.beginFrame = function () {
  8086. this._measureFps();
  8087. };
  8088. Engine.prototype.endFrame = function () {
  8089. //force a flush in case we are using a bad OS.
  8090. if (this._badOS) {
  8091. this.flushFramebuffer();
  8092. }
  8093. //submit frame to the vr device, if enabled
  8094. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8095. this._vrDisplayEnabled.submitFrame();
  8096. }
  8097. };
  8098. /**
  8099. * resize the view according to the canvas' size.
  8100. * @example
  8101. * window.addEventListener("resize", function () {
  8102. * engine.resize();
  8103. * });
  8104. */
  8105. Engine.prototype.resize = function () {
  8106. // We're not resizing the size of the canvas while in VR mode & presenting
  8107. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8108. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8109. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8110. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8111. }
  8112. };
  8113. /**
  8114. * force a specific size of the canvas
  8115. * @param {number} width - the new canvas' width
  8116. * @param {number} height - the new canvas' height
  8117. */
  8118. Engine.prototype.setSize = function (width, height) {
  8119. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8120. return;
  8121. }
  8122. this._renderingCanvas.width = width;
  8123. this._renderingCanvas.height = height;
  8124. for (var index = 0; index < this.scenes.length; index++) {
  8125. var scene = this.scenes[index];
  8126. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8127. var cam = scene.cameras[camIndex];
  8128. cam._currentRenderId = 0;
  8129. }
  8130. }
  8131. if (this.onResizeObservable.hasObservers) {
  8132. this.onResizeObservable.notifyObservers(this);
  8133. }
  8134. };
  8135. //WebVR functions
  8136. Engine.prototype.isVRDevicePresent = function (callback) {
  8137. this.getVRDevice(null, function (device) {
  8138. callback(device !== null);
  8139. });
  8140. };
  8141. Engine.prototype.getVRDevice = function (name, callback) {
  8142. if (!this.vrDisplaysPromise) {
  8143. callback(null);
  8144. return;
  8145. }
  8146. this.vrDisplaysPromise.then(function (devices) {
  8147. if (devices.length > 0) {
  8148. if (name) {
  8149. var found = devices.some(function (device) {
  8150. if (device.displayName === name) {
  8151. callback(device);
  8152. return true;
  8153. }
  8154. else {
  8155. return false;
  8156. }
  8157. });
  8158. if (!found) {
  8159. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8160. callback(devices[0]);
  8161. }
  8162. }
  8163. else {
  8164. //choose the first one
  8165. callback(devices[0]);
  8166. }
  8167. }
  8168. else {
  8169. BABYLON.Tools.Error("No WebVR devices found!");
  8170. callback(null);
  8171. }
  8172. });
  8173. };
  8174. Engine.prototype.initWebVR = function () {
  8175. if (!this.vrDisplaysPromise) {
  8176. this._getVRDisplays();
  8177. }
  8178. };
  8179. Engine.prototype.enableVR = function (vrDevice) {
  8180. this._vrDisplayEnabled = vrDevice;
  8181. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8182. };
  8183. Engine.prototype.disableVR = function () {
  8184. if (this._vrDisplayEnabled) {
  8185. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8186. }
  8187. };
  8188. Engine.prototype._getVRDisplays = function () {
  8189. var _this = this;
  8190. var getWebVRDevices = function (devices) {
  8191. var size = devices.length;
  8192. var i = 0;
  8193. _this._vrDisplays = devices.filter(function (device) {
  8194. return devices[i] instanceof VRDisplay;
  8195. });
  8196. return _this._vrDisplays;
  8197. };
  8198. //using a key due to typescript
  8199. if (navigator.getVRDisplays) {
  8200. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8201. }
  8202. };
  8203. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8204. this._currentRenderTarget = texture;
  8205. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8206. var gl = this._gl;
  8207. if (texture.isCube) {
  8208. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8209. }
  8210. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8211. this.wipeCaches();
  8212. };
  8213. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8214. if (this._currentFramebuffer !== framebuffer) {
  8215. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8216. this._currentFramebuffer = framebuffer;
  8217. }
  8218. };
  8219. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8220. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8221. this._currentRenderTarget = null;
  8222. // If MSAA, we need to bitblt back to main texture
  8223. var gl = this._gl;
  8224. if (texture._MSAAFramebuffer) {
  8225. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8226. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8227. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8228. }
  8229. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8230. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8231. gl.generateMipmap(gl.TEXTURE_2D);
  8232. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8233. }
  8234. if (onBeforeUnbind) {
  8235. if (texture._MSAAFramebuffer) {
  8236. // Bind the correct framebuffer
  8237. this.bindUnboundFramebuffer(texture._framebuffer);
  8238. }
  8239. onBeforeUnbind();
  8240. }
  8241. this.bindUnboundFramebuffer(null);
  8242. };
  8243. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8244. if (texture.generateMipMaps) {
  8245. var gl = this._gl;
  8246. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8247. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8248. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8249. }
  8250. };
  8251. Engine.prototype.flushFramebuffer = function () {
  8252. this._gl.flush();
  8253. };
  8254. Engine.prototype.restoreDefaultFramebuffer = function () {
  8255. this._currentRenderTarget = null;
  8256. this.bindUnboundFramebuffer(null);
  8257. this.setViewport(this._cachedViewport);
  8258. this.wipeCaches();
  8259. };
  8260. // UBOs
  8261. Engine.prototype.createUniformBuffer = function (elements) {
  8262. var ubo = this._gl.createBuffer();
  8263. this.bindUniformBuffer(ubo);
  8264. if (elements instanceof Float32Array) {
  8265. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8266. }
  8267. else {
  8268. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8269. }
  8270. this.bindUniformBuffer(null);
  8271. ubo.references = 1;
  8272. return ubo;
  8273. };
  8274. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8275. var ubo = this._gl.createBuffer();
  8276. this.bindUniformBuffer(ubo);
  8277. if (elements instanceof Float32Array) {
  8278. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8279. }
  8280. else {
  8281. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8282. }
  8283. this.bindUniformBuffer(null);
  8284. ubo.references = 1;
  8285. return ubo;
  8286. };
  8287. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8288. this.bindUniformBuffer(uniformBuffer);
  8289. if (offset === undefined) {
  8290. offset = 0;
  8291. }
  8292. if (count === undefined) {
  8293. if (elements instanceof Float32Array) {
  8294. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8295. }
  8296. else {
  8297. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8298. }
  8299. }
  8300. else {
  8301. if (elements instanceof Float32Array) {
  8302. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8303. }
  8304. else {
  8305. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8306. }
  8307. }
  8308. this.bindUniformBuffer(null);
  8309. };
  8310. // VBOs
  8311. Engine.prototype._resetVertexBufferBinding = function () {
  8312. this.bindArrayBuffer(null);
  8313. this._cachedVertexBuffers = null;
  8314. };
  8315. Engine.prototype.createVertexBuffer = function (vertices) {
  8316. var vbo = this._gl.createBuffer();
  8317. this.bindArrayBuffer(vbo);
  8318. if (vertices instanceof Float32Array) {
  8319. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8320. }
  8321. else {
  8322. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8323. }
  8324. this._resetVertexBufferBinding();
  8325. vbo.references = 1;
  8326. return vbo;
  8327. };
  8328. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8329. var vbo = this._gl.createBuffer();
  8330. this.bindArrayBuffer(vbo);
  8331. if (vertices instanceof Float32Array) {
  8332. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8333. }
  8334. else {
  8335. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8336. }
  8337. this._resetVertexBufferBinding();
  8338. vbo.references = 1;
  8339. return vbo;
  8340. };
  8341. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8342. this.bindArrayBuffer(vertexBuffer);
  8343. if (offset === undefined) {
  8344. offset = 0;
  8345. }
  8346. if (count === undefined) {
  8347. if (vertices instanceof Float32Array) {
  8348. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8349. }
  8350. else {
  8351. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8352. }
  8353. }
  8354. else {
  8355. if (vertices instanceof Float32Array) {
  8356. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8357. }
  8358. else {
  8359. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8360. }
  8361. }
  8362. this._resetVertexBufferBinding();
  8363. };
  8364. Engine.prototype._resetIndexBufferBinding = function () {
  8365. this.bindIndexBuffer(null);
  8366. this._cachedIndexBuffer = null;
  8367. };
  8368. Engine.prototype.createIndexBuffer = function (indices) {
  8369. var vbo = this._gl.createBuffer();
  8370. this.bindIndexBuffer(vbo);
  8371. // Check for 32 bits indices
  8372. var arrayBuffer;
  8373. var need32Bits = false;
  8374. if (indices instanceof Uint16Array) {
  8375. arrayBuffer = indices;
  8376. }
  8377. else {
  8378. //check 32 bit support
  8379. if (this._caps.uintIndices) {
  8380. if (indices instanceof Uint32Array) {
  8381. arrayBuffer = indices;
  8382. need32Bits = true;
  8383. }
  8384. else {
  8385. //number[] or Int32Array, check if 32 bit is necessary
  8386. for (var index = 0; index < indices.length; index++) {
  8387. if (indices[index] > 65535) {
  8388. need32Bits = true;
  8389. break;
  8390. }
  8391. }
  8392. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8393. }
  8394. }
  8395. else {
  8396. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8397. arrayBuffer = new Uint16Array(indices);
  8398. }
  8399. }
  8400. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8401. this._resetIndexBufferBinding();
  8402. vbo.references = 1;
  8403. vbo.is32Bits = need32Bits;
  8404. return vbo;
  8405. };
  8406. Engine.prototype.bindArrayBuffer = function (buffer) {
  8407. if (!this._vaoRecordInProgress) {
  8408. this._unBindVertexArrayObject();
  8409. }
  8410. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8411. };
  8412. Engine.prototype.bindUniformBuffer = function (buffer) {
  8413. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8414. };
  8415. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8416. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8417. };
  8418. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8419. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8420. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8421. };
  8422. ;
  8423. Engine.prototype.bindIndexBuffer = function (buffer) {
  8424. if (!this._vaoRecordInProgress) {
  8425. this._unBindVertexArrayObject();
  8426. }
  8427. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8428. };
  8429. Engine.prototype.bindBuffer = function (buffer, target) {
  8430. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8431. this._gl.bindBuffer(target, buffer);
  8432. this._currentBoundBuffer[target] = buffer;
  8433. }
  8434. };
  8435. Engine.prototype.updateArrayBuffer = function (data) {
  8436. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8437. };
  8438. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8439. var pointer = this._currentBufferPointers[indx];
  8440. var changed = false;
  8441. if (!pointer) {
  8442. changed = true;
  8443. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8444. }
  8445. else {
  8446. if (pointer.buffer !== buffer) {
  8447. pointer.buffer = buffer;
  8448. changed = true;
  8449. }
  8450. if (pointer.size !== size) {
  8451. pointer.size = size;
  8452. changed = true;
  8453. }
  8454. if (pointer.type !== type) {
  8455. pointer.type = type;
  8456. changed = true;
  8457. }
  8458. if (pointer.normalized !== normalized) {
  8459. pointer.normalized = normalized;
  8460. changed = true;
  8461. }
  8462. if (pointer.stride !== stride) {
  8463. pointer.stride = stride;
  8464. changed = true;
  8465. }
  8466. if (pointer.offset !== offset) {
  8467. pointer.offset = offset;
  8468. changed = true;
  8469. }
  8470. }
  8471. if (changed || this._vaoRecordInProgress) {
  8472. this.bindArrayBuffer(buffer);
  8473. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8474. }
  8475. };
  8476. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8477. if (indexBuffer == null) {
  8478. return;
  8479. }
  8480. if (this._cachedIndexBuffer !== indexBuffer) {
  8481. this._cachedIndexBuffer = indexBuffer;
  8482. this.bindIndexBuffer(indexBuffer);
  8483. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8484. }
  8485. };
  8486. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8487. var attributes = effect.getAttributesNames();
  8488. if (!this._vaoRecordInProgress) {
  8489. this._unBindVertexArrayObject();
  8490. }
  8491. this.unbindAllAttributes();
  8492. for (var index = 0; index < attributes.length; index++) {
  8493. var order = effect.getAttributeLocation(index);
  8494. if (order >= 0) {
  8495. var vertexBuffer = vertexBuffers[attributes[index]];
  8496. if (!vertexBuffer) {
  8497. continue;
  8498. }
  8499. this._gl.enableVertexAttribArray(order);
  8500. if (!this._vaoRecordInProgress) {
  8501. this._vertexAttribArraysEnabled[order] = true;
  8502. }
  8503. var buffer = vertexBuffer.getBuffer();
  8504. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8505. if (vertexBuffer.getIsInstanced()) {
  8506. this._gl.vertexAttribDivisor(order, 1);
  8507. if (!this._vaoRecordInProgress) {
  8508. this._currentInstanceLocations.push(order);
  8509. this._currentInstanceBuffers.push(buffer);
  8510. }
  8511. }
  8512. }
  8513. }
  8514. };
  8515. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8516. var vao = this._gl.createVertexArray();
  8517. this._vaoRecordInProgress = true;
  8518. this._gl.bindVertexArray(vao);
  8519. this._mustWipeVertexAttributes = true;
  8520. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8521. this.bindIndexBuffer(indexBuffer);
  8522. this._vaoRecordInProgress = false;
  8523. this._gl.bindVertexArray(null);
  8524. return vao;
  8525. };
  8526. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8527. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8528. this._cachedVertexArrayObject = vertexArrayObject;
  8529. this._gl.bindVertexArray(vertexArrayObject);
  8530. this._cachedVertexBuffers = null;
  8531. this._cachedIndexBuffer = null;
  8532. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8533. this._mustWipeVertexAttributes = true;
  8534. }
  8535. };
  8536. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8537. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8538. this._cachedVertexBuffers = vertexBuffer;
  8539. this._cachedEffectForVertexBuffers = effect;
  8540. var attributesCount = effect.getAttributesCount();
  8541. this._unBindVertexArrayObject();
  8542. this.unbindAllAttributes();
  8543. var offset = 0;
  8544. for (var index = 0; index < attributesCount; index++) {
  8545. if (index < vertexDeclaration.length) {
  8546. var order = effect.getAttributeLocation(index);
  8547. if (order >= 0) {
  8548. this._gl.enableVertexAttribArray(order);
  8549. this._vertexAttribArraysEnabled[order] = true;
  8550. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8551. }
  8552. offset += vertexDeclaration[index] * 4;
  8553. }
  8554. }
  8555. }
  8556. this._bindIndexBufferWithCache(indexBuffer);
  8557. };
  8558. Engine.prototype._unBindVertexArrayObject = function () {
  8559. if (!this._cachedVertexArrayObject) {
  8560. return;
  8561. }
  8562. this._cachedVertexArrayObject = null;
  8563. this._gl.bindVertexArray(null);
  8564. };
  8565. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8566. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8567. this._cachedVertexBuffers = vertexBuffers;
  8568. this._cachedEffectForVertexBuffers = effect;
  8569. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8570. }
  8571. this._bindIndexBufferWithCache(indexBuffer);
  8572. };
  8573. Engine.prototype.unbindInstanceAttributes = function () {
  8574. var boundBuffer;
  8575. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8576. var instancesBuffer = this._currentInstanceBuffers[i];
  8577. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8578. boundBuffer = instancesBuffer;
  8579. this.bindArrayBuffer(instancesBuffer);
  8580. }
  8581. var offsetLocation = this._currentInstanceLocations[i];
  8582. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8583. }
  8584. this._currentInstanceBuffers.length = 0;
  8585. this._currentInstanceLocations.length = 0;
  8586. };
  8587. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8588. this._gl.deleteVertexArray(vao);
  8589. };
  8590. Engine.prototype._releaseBuffer = function (buffer) {
  8591. buffer.references--;
  8592. if (buffer.references === 0) {
  8593. this._gl.deleteBuffer(buffer);
  8594. return true;
  8595. }
  8596. return false;
  8597. };
  8598. Engine.prototype.createInstancesBuffer = function (capacity) {
  8599. var buffer = this._gl.createBuffer();
  8600. buffer.capacity = capacity;
  8601. this.bindArrayBuffer(buffer);
  8602. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8603. return buffer;
  8604. };
  8605. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8606. this._gl.deleteBuffer(buffer);
  8607. };
  8608. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8609. this.bindArrayBuffer(instancesBuffer);
  8610. if (data) {
  8611. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8612. }
  8613. if (offsetLocations[0].index !== undefined) {
  8614. var stride = 0;
  8615. for (var i = 0; i < offsetLocations.length; i++) {
  8616. var ai = offsetLocations[i];
  8617. stride += ai.attributeSize * 4;
  8618. }
  8619. for (var i = 0; i < offsetLocations.length; i++) {
  8620. var ai = offsetLocations[i];
  8621. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8622. this._gl.enableVertexAttribArray(ai.index);
  8623. this._vertexAttribArraysEnabled[ai.index] = true;
  8624. }
  8625. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8626. this._gl.vertexAttribDivisor(ai.index, 1);
  8627. this._currentInstanceLocations.push(ai.index);
  8628. this._currentInstanceBuffers.push(instancesBuffer);
  8629. }
  8630. }
  8631. else {
  8632. for (var index = 0; index < 4; index++) {
  8633. var offsetLocation = offsetLocations[index];
  8634. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8635. this._gl.enableVertexAttribArray(offsetLocation);
  8636. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8637. }
  8638. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8639. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8640. this._currentInstanceLocations.push(offsetLocation);
  8641. this._currentInstanceBuffers.push(instancesBuffer);
  8642. }
  8643. }
  8644. };
  8645. Engine.prototype.applyStates = function () {
  8646. this._depthCullingState.apply(this._gl);
  8647. this._stencilState.apply(this._gl);
  8648. this._alphaState.apply(this._gl);
  8649. };
  8650. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8651. // Apply states
  8652. this.applyStates();
  8653. this._drawCalls.addCount(1, false);
  8654. // Render
  8655. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8656. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8657. if (instancesCount) {
  8658. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8659. return;
  8660. }
  8661. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8662. };
  8663. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8664. // Apply states
  8665. this.applyStates();
  8666. this._drawCalls.addCount(1, false);
  8667. if (instancesCount) {
  8668. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8669. return;
  8670. }
  8671. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8672. };
  8673. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8674. // Apply states
  8675. this.applyStates();
  8676. this._drawCalls.addCount(1, false);
  8677. if (instancesCount) {
  8678. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8679. return;
  8680. }
  8681. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8682. };
  8683. // Shaders
  8684. Engine.prototype._releaseEffect = function (effect) {
  8685. if (this._compiledEffects[effect._key]) {
  8686. delete this._compiledEffects[effect._key];
  8687. if (effect.getProgram()) {
  8688. this._gl.deleteProgram(effect.getProgram());
  8689. }
  8690. }
  8691. };
  8692. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8693. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8694. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8695. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8696. if (this._compiledEffects[name]) {
  8697. return this._compiledEffects[name];
  8698. }
  8699. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8700. effect._key = name;
  8701. this._compiledEffects[name] = effect;
  8702. return effect;
  8703. };
  8704. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8705. if (uniformsNames === void 0) { uniformsNames = []; }
  8706. if (samplers === void 0) { samplers = []; }
  8707. if (defines === void 0) { defines = ""; }
  8708. return this.createEffect({
  8709. vertex: "particles",
  8710. fragmentElement: fragmentName
  8711. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8712. };
  8713. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8714. context = context || this._gl;
  8715. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8716. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8717. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8718. var shaderProgram = context.createProgram();
  8719. context.attachShader(shaderProgram, vertexShader);
  8720. context.attachShader(shaderProgram, fragmentShader);
  8721. context.linkProgram(shaderProgram);
  8722. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8723. if (!linked) {
  8724. var error = context.getProgramInfoLog(shaderProgram);
  8725. if (error) {
  8726. throw new Error(error);
  8727. }
  8728. }
  8729. context.deleteShader(vertexShader);
  8730. context.deleteShader(fragmentShader);
  8731. return shaderProgram;
  8732. };
  8733. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8734. var results = [];
  8735. for (var index = 0; index < uniformsNames.length; index++) {
  8736. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8737. }
  8738. return results;
  8739. };
  8740. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8741. var results = [];
  8742. for (var index = 0; index < attributesNames.length; index++) {
  8743. try {
  8744. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8745. }
  8746. catch (e) {
  8747. results.push(-1);
  8748. }
  8749. }
  8750. return results;
  8751. };
  8752. Engine.prototype.enableEffect = function (effect) {
  8753. // Use program
  8754. this.setProgram(effect.getProgram());
  8755. this._currentEffect = effect;
  8756. if (effect.onBind) {
  8757. effect.onBind(effect);
  8758. }
  8759. };
  8760. Engine.prototype.setIntArray = function (uniform, array) {
  8761. if (!uniform)
  8762. return;
  8763. this._gl.uniform1iv(uniform, array);
  8764. };
  8765. Engine.prototype.setIntArray2 = function (uniform, array) {
  8766. if (!uniform || array.length % 2 !== 0)
  8767. return;
  8768. this._gl.uniform2iv(uniform, array);
  8769. };
  8770. Engine.prototype.setIntArray3 = function (uniform, array) {
  8771. if (!uniform || array.length % 3 !== 0)
  8772. return;
  8773. this._gl.uniform3iv(uniform, array);
  8774. };
  8775. Engine.prototype.setIntArray4 = function (uniform, array) {
  8776. if (!uniform || array.length % 4 !== 0)
  8777. return;
  8778. this._gl.uniform4iv(uniform, array);
  8779. };
  8780. Engine.prototype.setFloatArray = function (uniform, array) {
  8781. if (!uniform)
  8782. return;
  8783. this._gl.uniform1fv(uniform, array);
  8784. };
  8785. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8786. if (!uniform || array.length % 2 !== 0)
  8787. return;
  8788. this._gl.uniform2fv(uniform, array);
  8789. };
  8790. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8791. if (!uniform || array.length % 3 !== 0)
  8792. return;
  8793. this._gl.uniform3fv(uniform, array);
  8794. };
  8795. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8796. if (!uniform || array.length % 4 !== 0)
  8797. return;
  8798. this._gl.uniform4fv(uniform, array);
  8799. };
  8800. Engine.prototype.setArray = function (uniform, array) {
  8801. if (!uniform)
  8802. return;
  8803. this._gl.uniform1fv(uniform, array);
  8804. };
  8805. Engine.prototype.setArray2 = function (uniform, array) {
  8806. if (!uniform || array.length % 2 !== 0)
  8807. return;
  8808. this._gl.uniform2fv(uniform, array);
  8809. };
  8810. Engine.prototype.setArray3 = function (uniform, array) {
  8811. if (!uniform || array.length % 3 !== 0)
  8812. return;
  8813. this._gl.uniform3fv(uniform, array);
  8814. };
  8815. Engine.prototype.setArray4 = function (uniform, array) {
  8816. if (!uniform || array.length % 4 !== 0)
  8817. return;
  8818. this._gl.uniform4fv(uniform, array);
  8819. };
  8820. Engine.prototype.setMatrices = function (uniform, matrices) {
  8821. if (!uniform)
  8822. return;
  8823. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8824. };
  8825. Engine.prototype.setMatrix = function (uniform, matrix) {
  8826. if (!uniform)
  8827. return;
  8828. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8829. };
  8830. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8831. if (!uniform)
  8832. return;
  8833. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8834. };
  8835. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8836. if (!uniform)
  8837. return;
  8838. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8839. };
  8840. Engine.prototype.setFloat = function (uniform, value) {
  8841. if (!uniform)
  8842. return;
  8843. this._gl.uniform1f(uniform, value);
  8844. };
  8845. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8846. if (!uniform)
  8847. return;
  8848. this._gl.uniform2f(uniform, x, y);
  8849. };
  8850. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8851. if (!uniform)
  8852. return;
  8853. this._gl.uniform3f(uniform, x, y, z);
  8854. };
  8855. Engine.prototype.setBool = function (uniform, bool) {
  8856. if (!uniform)
  8857. return;
  8858. this._gl.uniform1i(uniform, bool);
  8859. };
  8860. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8861. if (!uniform)
  8862. return;
  8863. this._gl.uniform4f(uniform, x, y, z, w);
  8864. };
  8865. Engine.prototype.setColor3 = function (uniform, color3) {
  8866. if (!uniform)
  8867. return;
  8868. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8869. };
  8870. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8871. if (!uniform)
  8872. return;
  8873. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8874. };
  8875. // States
  8876. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8877. if (zOffset === void 0) { zOffset = 0; }
  8878. if (reverseSide === void 0) { reverseSide = false; }
  8879. // Culling
  8880. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8881. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8882. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8883. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8884. if (culling) {
  8885. this._depthCullingState.cullFace = cullFace;
  8886. this._depthCullingState.cull = true;
  8887. }
  8888. else {
  8889. this._depthCullingState.cull = false;
  8890. }
  8891. }
  8892. // Z offset
  8893. this.setZOffset(zOffset);
  8894. };
  8895. Engine.prototype.setZOffset = function (value) {
  8896. this._depthCullingState.zOffset = value;
  8897. };
  8898. Engine.prototype.getZOffset = function () {
  8899. return this._depthCullingState.zOffset;
  8900. };
  8901. Engine.prototype.setDepthBuffer = function (enable) {
  8902. this._depthCullingState.depthTest = enable;
  8903. };
  8904. Engine.prototype.getDepthWrite = function () {
  8905. return this._depthCullingState.depthMask;
  8906. };
  8907. Engine.prototype.setDepthWrite = function (enable) {
  8908. this._depthCullingState.depthMask = enable;
  8909. };
  8910. Engine.prototype.setColorWrite = function (enable) {
  8911. this._gl.colorMask(enable, enable, enable, enable);
  8912. };
  8913. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8914. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8915. };
  8916. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8917. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8918. if (this._alphaMode === mode) {
  8919. return;
  8920. }
  8921. switch (mode) {
  8922. case Engine.ALPHA_DISABLE:
  8923. this._alphaState.alphaBlend = false;
  8924. break;
  8925. case Engine.ALPHA_PREMULTIPLIED:
  8926. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8927. this._alphaState.alphaBlend = true;
  8928. break;
  8929. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8930. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8931. this._alphaState.alphaBlend = true;
  8932. break;
  8933. case Engine.ALPHA_COMBINE:
  8934. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8935. this._alphaState.alphaBlend = true;
  8936. break;
  8937. case Engine.ALPHA_ONEONE:
  8938. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8939. this._alphaState.alphaBlend = true;
  8940. break;
  8941. case Engine.ALPHA_ADD:
  8942. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8943. this._alphaState.alphaBlend = true;
  8944. break;
  8945. case Engine.ALPHA_SUBTRACT:
  8946. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8947. this._alphaState.alphaBlend = true;
  8948. break;
  8949. case Engine.ALPHA_MULTIPLY:
  8950. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8951. this._alphaState.alphaBlend = true;
  8952. break;
  8953. case Engine.ALPHA_MAXIMIZED:
  8954. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8955. this._alphaState.alphaBlend = true;
  8956. break;
  8957. case Engine.ALPHA_INTERPOLATE:
  8958. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  8959. this._alphaState.alphaBlend = true;
  8960. break;
  8961. case Engine.ALPHA_SCREENMODE:
  8962. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8963. this._alphaState.alphaBlend = true;
  8964. break;
  8965. }
  8966. if (!noDepthWriteChange) {
  8967. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8968. }
  8969. this._alphaMode = mode;
  8970. };
  8971. Engine.prototype.getAlphaMode = function () {
  8972. return this._alphaMode;
  8973. };
  8974. Engine.prototype.setAlphaTesting = function (enable) {
  8975. this._alphaTest = enable;
  8976. };
  8977. Engine.prototype.getAlphaTesting = function () {
  8978. return !!this._alphaTest;
  8979. };
  8980. // Textures
  8981. Engine.prototype.wipeCaches = function (bruteForce) {
  8982. if (this.preventCacheWipeBetweenFrames) {
  8983. return;
  8984. }
  8985. this.resetTextureCache();
  8986. this._currentEffect = null;
  8987. // 6/8/2017: deltakosh: Should not be required anymore.
  8988. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  8989. if (bruteForce) {
  8990. this._stencilState.reset();
  8991. this._depthCullingState.reset();
  8992. this.setDepthFunctionToLessOrEqual();
  8993. this._alphaState.reset();
  8994. }
  8995. this._cachedVertexBuffers = null;
  8996. this._cachedIndexBuffer = null;
  8997. this._cachedEffectForVertexBuffers = null;
  8998. this._unBindVertexArrayObject();
  8999. this.bindIndexBuffer(null);
  9000. this.bindArrayBuffer(null);
  9001. };
  9002. /**
  9003. * Set the compressed texture format to use, based on the formats you have, and the formats
  9004. * supported by the hardware / browser.
  9005. *
  9006. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9007. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9008. * to API arguments needed to compressed textures. This puts the burden on the container
  9009. * generator to house the arcane code for determining these for current & future formats.
  9010. *
  9011. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9012. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9013. *
  9014. * Note: The result of this call is not taken into account when a texture is base64.
  9015. *
  9016. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9017. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9018. *
  9019. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9020. * @returns The extension selected.
  9021. */
  9022. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9023. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9024. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9025. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9026. return this._textureFormatInUse = this._texturesSupported[i];
  9027. }
  9028. }
  9029. }
  9030. // actively set format to nothing, to allow this to be called more than once
  9031. // and possibly fail the 2nd time
  9032. return this._textureFormatInUse = null;
  9033. };
  9034. /**
  9035. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9036. * @param {string} urlArg- This contains one of the following:
  9037. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9038. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9039. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9040. *
  9041. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9042. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9043. * @param {Scene} scene- Needed for loading to the correct scene.
  9044. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9045. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9046. * @param {callback} onError- Optional callback to be called upon failure.
  9047. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9048. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9049. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9050. *
  9051. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9052. */
  9053. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9054. var _this = this;
  9055. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9056. if (onLoad === void 0) { onLoad = null; }
  9057. if (onError === void 0) { onError = null; }
  9058. if (buffer === void 0) { buffer = null; }
  9059. var texture = fallBack ? fallBack : this._gl.createTexture();
  9060. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9061. var fromData = url.substr(0, 5) === "data:";
  9062. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9063. // establish the file extension, if possible
  9064. var lastDot = url.lastIndexOf('.');
  9065. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9066. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9067. if (isDDS) {
  9068. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9069. }
  9070. var isTGA = (extension === ".tga");
  9071. // determine if a ktx file should be substituted
  9072. var isKTX = false;
  9073. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9074. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9075. isKTX = true;
  9076. }
  9077. scene._addPendingData(texture);
  9078. texture.url = url;
  9079. texture.noMipmap = noMipmap;
  9080. texture.references = 1;
  9081. texture.samplingMode = samplingMode;
  9082. texture.onLoadedCallbacks = [];
  9083. if (onLoad) {
  9084. texture.onLoadedCallbacks.push(onLoad);
  9085. }
  9086. if (!fallBack)
  9087. this._loadedTexturesCache.push(texture);
  9088. var onerror = function () {
  9089. scene._removePendingData(texture);
  9090. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9091. if (isKTX) {
  9092. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9093. }
  9094. else if (onError) {
  9095. onError();
  9096. }
  9097. };
  9098. var callback;
  9099. // processing for non-image formats
  9100. if (isKTX || isTGA || isDDS) {
  9101. if (isKTX) {
  9102. callback = function (data) {
  9103. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9104. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9105. ktx.uploadLevels(_this._gl, !noMipmap);
  9106. }, samplingMode);
  9107. };
  9108. }
  9109. else if (isTGA) {
  9110. callback = function (arrayBuffer) {
  9111. var data = new Uint8Array(arrayBuffer);
  9112. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9113. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9114. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9115. }, samplingMode);
  9116. };
  9117. }
  9118. else if (isDDS) {
  9119. callback = function (data) {
  9120. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9121. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9122. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9123. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9124. }, samplingMode);
  9125. };
  9126. }
  9127. if (!buffer) {
  9128. BABYLON.Tools.LoadFile(url, function (data) {
  9129. callback(data);
  9130. }, null, scene.database, true, onerror);
  9131. }
  9132. else {
  9133. callback(buffer);
  9134. }
  9135. // image format processing
  9136. }
  9137. else {
  9138. var onload = function (img) {
  9139. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9140. var isPot = (img.width === potWidth && img.height === potHeight);
  9141. if (!isPot) {
  9142. _this._prepareWorkingCanvas();
  9143. _this._workingCanvas.width = potWidth;
  9144. _this._workingCanvas.height = potHeight;
  9145. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9146. _this._workingContext.imageSmoothingEnabled = false;
  9147. _this._workingContext.mozImageSmoothingEnabled = false;
  9148. _this._workingContext.oImageSmoothingEnabled = false;
  9149. _this._workingContext.webkitImageSmoothingEnabled = false;
  9150. _this._workingContext.msImageSmoothingEnabled = false;
  9151. }
  9152. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9153. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9154. _this._workingContext.imageSmoothingEnabled = true;
  9155. _this._workingContext.mozImageSmoothingEnabled = true;
  9156. _this._workingContext.oImageSmoothingEnabled = true;
  9157. _this._workingContext.webkitImageSmoothingEnabled = true;
  9158. _this._workingContext.msImageSmoothingEnabled = true;
  9159. }
  9160. }
  9161. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9162. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9163. }, samplingMode);
  9164. };
  9165. if (!fromData || isBase64)
  9166. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9167. else if (buffer instanceof Array || typeof buffer === "string")
  9168. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9169. else
  9170. onload(buffer);
  9171. }
  9172. return texture;
  9173. };
  9174. Engine.prototype._getInternalFormat = function (format) {
  9175. var internalFormat = this._gl.RGBA;
  9176. switch (format) {
  9177. case Engine.TEXTUREFORMAT_ALPHA:
  9178. internalFormat = this._gl.ALPHA;
  9179. break;
  9180. case Engine.TEXTUREFORMAT_LUMINANCE:
  9181. internalFormat = this._gl.LUMINANCE;
  9182. break;
  9183. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9184. internalFormat = this._gl.LUMINANCE_ALPHA;
  9185. break;
  9186. case Engine.TEXTUREFORMAT_RGB:
  9187. internalFormat = this._gl.RGB;
  9188. break;
  9189. case Engine.TEXTUREFORMAT_RGBA:
  9190. internalFormat = this._gl.RGBA;
  9191. break;
  9192. }
  9193. return internalFormat;
  9194. };
  9195. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9196. if (compression === void 0) { compression = null; }
  9197. var internalFormat = this._getInternalFormat(format);
  9198. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9199. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9200. if (texture._width % 4 !== 0) {
  9201. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9202. }
  9203. if (compression) {
  9204. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9205. }
  9206. else {
  9207. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9208. }
  9209. if (texture.generateMipMaps) {
  9210. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9211. }
  9212. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9213. this.resetTextureCache();
  9214. texture.isReady = true;
  9215. };
  9216. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9217. if (compression === void 0) { compression = null; }
  9218. var texture = this._gl.createTexture();
  9219. texture._baseWidth = width;
  9220. texture._baseHeight = height;
  9221. texture._width = width;
  9222. texture._height = height;
  9223. texture.references = 1;
  9224. this.updateRawTexture(texture, data, format, invertY, compression);
  9225. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9226. // Filters
  9227. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9228. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9229. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9230. if (generateMipMaps) {
  9231. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9232. }
  9233. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9234. texture.samplingMode = samplingMode;
  9235. this._loadedTexturesCache.push(texture);
  9236. return texture;
  9237. };
  9238. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9239. var texture = this._gl.createTexture();
  9240. texture._baseWidth = width;
  9241. texture._baseHeight = height;
  9242. if (generateMipMaps) {
  9243. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9244. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9245. }
  9246. this.resetTextureCache();
  9247. texture._width = width;
  9248. texture._height = height;
  9249. texture.isReady = false;
  9250. texture.generateMipMaps = generateMipMaps;
  9251. texture.references = 1;
  9252. texture.samplingMode = samplingMode;
  9253. this.updateTextureSamplingMode(samplingMode, texture);
  9254. this._loadedTexturesCache.push(texture);
  9255. return texture;
  9256. };
  9257. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9258. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9259. if (texture.isCube) {
  9260. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9261. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9262. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9263. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9264. }
  9265. else {
  9266. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9267. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9268. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9269. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9270. }
  9271. texture.samplingMode = samplingMode;
  9272. };
  9273. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9274. if (premulAlpha === void 0) { premulAlpha = false; }
  9275. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9276. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9277. if (premulAlpha) {
  9278. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9279. }
  9280. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9281. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9282. if (texture.generateMipMaps) {
  9283. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9284. }
  9285. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9286. if (premulAlpha) {
  9287. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9288. }
  9289. this.resetTextureCache();
  9290. texture.isReady = true;
  9291. };
  9292. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9293. if (texture._isDisabled) {
  9294. return;
  9295. }
  9296. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9297. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9298. try {
  9299. // Testing video texture support
  9300. if (this._videoTextureSupported === undefined) {
  9301. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9302. if (this._gl.getError() !== 0) {
  9303. this._videoTextureSupported = false;
  9304. }
  9305. else {
  9306. this._videoTextureSupported = true;
  9307. }
  9308. }
  9309. // Copy video through the current working canvas if video texture is not supported
  9310. if (!this._videoTextureSupported) {
  9311. if (!texture._workingCanvas) {
  9312. texture._workingCanvas = document.createElement("canvas");
  9313. texture._workingContext = texture._workingCanvas.getContext("2d");
  9314. texture._workingCanvas.width = texture._width;
  9315. texture._workingCanvas.height = texture._height;
  9316. }
  9317. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9318. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9319. }
  9320. else {
  9321. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9322. }
  9323. if (texture.generateMipMaps) {
  9324. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9325. }
  9326. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9327. this.resetTextureCache();
  9328. texture.isReady = true;
  9329. }
  9330. catch (ex) {
  9331. // Something unexpected
  9332. // Let's disable the texture
  9333. texture._isDisabled = true;
  9334. }
  9335. };
  9336. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9337. // old version had a "generateMipMaps" arg instead of options.
  9338. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9339. // in the same way, generateDepthBuffer is defaulted to true
  9340. var generateMipMaps = false;
  9341. var generateDepthBuffer = true;
  9342. var generateStencilBuffer = false;
  9343. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9344. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9345. if (options !== undefined) {
  9346. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9347. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9348. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9349. type = options.type === undefined ? type : options.type;
  9350. if (options.samplingMode !== undefined) {
  9351. samplingMode = options.samplingMode;
  9352. }
  9353. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9354. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9355. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9356. }
  9357. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9358. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9359. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9360. }
  9361. }
  9362. var gl = this._gl;
  9363. var texture = gl.createTexture();
  9364. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9365. var width = size.width || size;
  9366. var height = size.height || size;
  9367. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9368. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9369. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9370. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9371. }
  9372. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9373. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9374. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9376. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9377. // Create the framebuffer
  9378. var framebuffer = gl.createFramebuffer();
  9379. this.bindUnboundFramebuffer(framebuffer);
  9380. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9381. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9382. if (generateMipMaps) {
  9383. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9384. }
  9385. // Unbind
  9386. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9387. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9388. this.bindUnboundFramebuffer(null);
  9389. texture._framebuffer = framebuffer;
  9390. texture._baseWidth = width;
  9391. texture._baseHeight = height;
  9392. texture._width = width;
  9393. texture._height = height;
  9394. texture.isReady = true;
  9395. texture.samples = 1;
  9396. texture.generateMipMaps = generateMipMaps;
  9397. texture.references = 1;
  9398. texture.samplingMode = samplingMode;
  9399. texture.type = type;
  9400. texture._generateDepthBuffer = generateDepthBuffer;
  9401. texture._generateStencilBuffer = generateStencilBuffer;
  9402. this.resetTextureCache();
  9403. this._loadedTexturesCache.push(texture);
  9404. return texture;
  9405. };
  9406. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9407. var generateMipMaps = false;
  9408. var generateDepthBuffer = true;
  9409. var generateStencilBuffer = false;
  9410. var generateDepthTexture = false;
  9411. var textureCount = 1;
  9412. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9413. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9414. var types = [], samplingModes = [];
  9415. if (options !== undefined) {
  9416. generateMipMaps = options.generateMipMaps;
  9417. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9418. generateStencilBuffer = options.generateStencilBuffer;
  9419. generateDepthTexture = options.generateDepthTexture;
  9420. textureCount = options.textureCount || 1;
  9421. if (options.types) {
  9422. types = options.types;
  9423. }
  9424. if (options.samplingModes) {
  9425. samplingModes = options.samplingModes;
  9426. }
  9427. }
  9428. var gl = this._gl;
  9429. // Create the framebuffer
  9430. var framebuffer = gl.createFramebuffer();
  9431. this.bindUnboundFramebuffer(framebuffer);
  9432. var colorRenderbuffer = gl.createRenderbuffer();
  9433. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9434. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, width, height);
  9435. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  9436. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9437. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.RENDERBUFFER, colorRenderbuffer);
  9438. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, colorRenderbuffer);
  9439. var width = size.width || size;
  9440. var height = size.height || size;
  9441. var textures = [];
  9442. var attachments = [];
  9443. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9444. for (var i = 0; i < textureCount; i++) {
  9445. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9446. var type = types[i] || defaultType;
  9447. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9448. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9449. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9450. }
  9451. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9452. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9453. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9454. }
  9455. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9456. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9457. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9458. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9459. }
  9460. var texture = gl.createTexture();
  9461. var attachment = gl["COLOR_ATTACHMENT" + i];
  9462. textures.push(texture);
  9463. attachments.push(attachment);
  9464. gl.activeTexture(gl["TEXTURE" + i]);
  9465. gl.bindTexture(gl.TEXTURE_2D, texture);
  9466. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9467. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9468. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9469. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9470. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9471. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9472. if (generateMipMaps) {
  9473. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9474. }
  9475. // Unbind
  9476. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9477. texture._framebuffer = framebuffer;
  9478. texture._depthStencilBuffer = depthStencilBuffer;
  9479. texture._baseWidth = width;
  9480. texture._baseHeight = height;
  9481. texture._width = width;
  9482. texture._height = height;
  9483. texture.isReady = true;
  9484. texture.samples = 1;
  9485. texture.generateMipMaps = generateMipMaps;
  9486. texture.references = 1;
  9487. texture.samplingMode = samplingMode;
  9488. texture.type = type;
  9489. texture._generateDepthBuffer = generateDepthBuffer;
  9490. texture._generateStencilBuffer = generateStencilBuffer;
  9491. this._loadedTexturesCache.push(texture);
  9492. }
  9493. if (generateDepthTexture) {
  9494. // Depth texture
  9495. var depthTexture = gl.createTexture();
  9496. gl.activeTexture(gl.TEXTURE0);
  9497. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9498. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9501. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9502. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9503. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9504. depthTexture._framebuffer = framebuffer;
  9505. depthTexture._baseWidth = width;
  9506. depthTexture._baseHeight = height;
  9507. depthTexture._width = width;
  9508. depthTexture._height = height;
  9509. depthTexture.isReady = true;
  9510. depthTexture.samples = 1;
  9511. depthTexture.generateMipMaps = generateMipMaps;
  9512. depthTexture.references = 1;
  9513. depthTexture.samplingMode = gl.NEAREST;
  9514. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9515. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9516. textures.push(depthTexture);
  9517. this._loadedTexturesCache.push(depthTexture);
  9518. }
  9519. gl.drawBuffers(attachments);
  9520. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9521. this.bindUnboundFramebuffer(null);
  9522. this.resetTextureCache();
  9523. return textures;
  9524. };
  9525. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9526. if (samples === void 0) { samples = 1; }
  9527. var depthStencilBuffer = null;
  9528. var gl = this._gl;
  9529. // Create the depth/stencil buffer
  9530. if (generateStencilBuffer) {
  9531. depthStencilBuffer = gl.createRenderbuffer();
  9532. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9533. if (samples > 1) {
  9534. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9535. }
  9536. else {
  9537. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9538. }
  9539. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9540. }
  9541. else if (generateDepthBuffer) {
  9542. depthStencilBuffer = gl.createRenderbuffer();
  9543. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9544. if (samples > 1) {
  9545. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9546. }
  9547. else {
  9548. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9549. }
  9550. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9551. }
  9552. return depthStencilBuffer;
  9553. };
  9554. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9555. if (this.webGLVersion < 2) {
  9556. return 1;
  9557. }
  9558. if (texture.samples === samples) {
  9559. return samples;
  9560. }
  9561. var gl = this._gl;
  9562. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9563. // Dispose previous render buffers
  9564. if (texture._depthStencilBuffer) {
  9565. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9566. }
  9567. if (texture._MSAAFramebuffer) {
  9568. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9569. }
  9570. if (texture._MSAARenderBuffer) {
  9571. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9572. }
  9573. if (samples > 1) {
  9574. texture._MSAAFramebuffer = gl.createFramebuffer();
  9575. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9576. var colorRenderbuffer = gl.createRenderbuffer();
  9577. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9578. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9579. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9580. texture._MSAARenderBuffer = colorRenderbuffer;
  9581. }
  9582. else {
  9583. this.bindUnboundFramebuffer(texture._framebuffer);
  9584. }
  9585. texture.samples = samples;
  9586. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9587. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9588. this.bindUnboundFramebuffer(null);
  9589. return samples;
  9590. };
  9591. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9592. var gl = this._gl;
  9593. var texture = gl.createTexture();
  9594. var generateMipMaps = true;
  9595. var generateDepthBuffer = true;
  9596. var generateStencilBuffer = false;
  9597. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9598. if (options !== undefined) {
  9599. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9600. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9601. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9602. if (options.samplingMode !== undefined) {
  9603. samplingMode = options.samplingMode;
  9604. }
  9605. }
  9606. texture.isCube = true;
  9607. texture.references = 1;
  9608. texture.generateMipMaps = generateMipMaps;
  9609. texture.references = 1;
  9610. texture.samples = 1;
  9611. texture.samplingMode = samplingMode;
  9612. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9613. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9614. for (var face = 0; face < 6; face++) {
  9615. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9616. }
  9617. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9618. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9619. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9620. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9621. // Create the framebuffer
  9622. var framebuffer = gl.createFramebuffer();
  9623. this.bindUnboundFramebuffer(framebuffer);
  9624. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9625. // Mipmaps
  9626. if (texture.generateMipMaps) {
  9627. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9628. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9629. }
  9630. // Unbind
  9631. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9632. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9633. this.bindUnboundFramebuffer(null);
  9634. texture._framebuffer = framebuffer;
  9635. texture._width = size;
  9636. texture._height = size;
  9637. texture.isReady = true;
  9638. this.resetTextureCache();
  9639. this._loadedTexturesCache.push(texture);
  9640. return texture;
  9641. };
  9642. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9643. var _this = this;
  9644. if (onLoad === void 0) { onLoad = null; }
  9645. if (onError === void 0) { onError = null; }
  9646. var gl = this._gl;
  9647. var texture = gl.createTexture();
  9648. texture.isCube = true;
  9649. texture.url = rootUrl;
  9650. texture.references = 1;
  9651. texture.onLoadedCallbacks = [];
  9652. var isKTX = false;
  9653. var lastDot = rootUrl.lastIndexOf('.');
  9654. var extension = rootUrl.substring(lastDot).toLowerCase();
  9655. if (this._textureFormatInUse) {
  9656. extension = this._textureFormatInUse;
  9657. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9658. isKTX = true;
  9659. }
  9660. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9661. if (isDDS) {
  9662. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9663. }
  9664. if (isKTX) {
  9665. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9666. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9667. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9668. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9669. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9670. ktx.uploadLevels(_this._gl, !noMipmap);
  9671. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9672. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9673. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9674. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9675. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9676. _this.resetTextureCache();
  9677. texture._width = ktx.pixelWidth;
  9678. texture._height = ktx.pixelHeight;
  9679. texture.isReady = true;
  9680. }, null, null, true, onError);
  9681. }
  9682. else if (isDDS) {
  9683. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9684. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9685. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9686. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9687. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9688. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9689. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9690. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9691. }
  9692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9694. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9695. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9696. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9697. _this.resetTextureCache();
  9698. texture._width = info.width;
  9699. texture._height = info.height;
  9700. texture.isReady = true;
  9701. }, null, null, true, onError);
  9702. }
  9703. else {
  9704. cascadeLoad(rootUrl, scene, function (imgs) {
  9705. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9706. var height = width;
  9707. _this._prepareWorkingCanvas();
  9708. _this._workingCanvas.width = width;
  9709. _this._workingCanvas.height = height;
  9710. var faces = [
  9711. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9712. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9713. ];
  9714. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9715. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9716. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9717. for (var index = 0; index < faces.length; index++) {
  9718. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9719. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9720. }
  9721. if (!noMipmap) {
  9722. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9723. }
  9724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9725. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9726. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9728. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9729. _this.resetTextureCache();
  9730. texture._width = width;
  9731. texture._height = height;
  9732. texture.isReady = true;
  9733. texture.onLoadedCallbacks.forEach(function (callback) {
  9734. callback();
  9735. });
  9736. if (onLoad) {
  9737. onLoad();
  9738. }
  9739. }, files, onError);
  9740. }
  9741. this._loadedTexturesCache.push(texture);
  9742. return texture;
  9743. };
  9744. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9745. texture._width = width;
  9746. texture._height = height;
  9747. texture._size = width * height;
  9748. texture._baseWidth = width;
  9749. texture._baseHeight = height;
  9750. };
  9751. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9752. if (compression === void 0) { compression = null; }
  9753. if (level === void 0) { level = 0; }
  9754. var gl = this._gl;
  9755. var textureType = this._getWebGLTextureType(type);
  9756. var internalFormat = this._getInternalFormat(format);
  9757. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9758. var needConversion = false;
  9759. if (internalFormat === gl.RGB) {
  9760. internalFormat = gl.RGBA;
  9761. needConversion = true;
  9762. }
  9763. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9764. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9765. if (texture._width % 4 !== 0) {
  9766. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9767. }
  9768. var facesIndex = [
  9769. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9770. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9771. ];
  9772. // Data are known to be in +X +Y +Z -X -Y -Z
  9773. for (var index = 0; index < facesIndex.length; index++) {
  9774. var faceData = data[index];
  9775. if (compression) {
  9776. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9777. }
  9778. else {
  9779. if (needConversion) {
  9780. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9781. }
  9782. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9783. }
  9784. }
  9785. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9786. if (isPot && texture.generateMipMaps && level === 0) {
  9787. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9788. }
  9789. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9790. this.resetTextureCache();
  9791. texture.isReady = true;
  9792. };
  9793. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9794. if (compression === void 0) { compression = null; }
  9795. var gl = this._gl;
  9796. var texture = gl.createTexture();
  9797. texture.isCube = true;
  9798. texture.references = 1;
  9799. var textureType = this._getWebGLTextureType(type);
  9800. var internalFormat = this._getInternalFormat(format);
  9801. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9802. var needConversion = false;
  9803. if (internalFormat === gl.RGB) {
  9804. internalFormat = gl.RGBA;
  9805. needConversion = true;
  9806. }
  9807. var width = size;
  9808. var height = width;
  9809. texture._width = width;
  9810. texture._height = height;
  9811. // Double check on POT to generate Mips.
  9812. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9813. if (!isPot) {
  9814. generateMipMaps = false;
  9815. }
  9816. texture.generateMipMaps = generateMipMaps;
  9817. // Upload data if needed. The texture won t be ready until then.
  9818. if (data) {
  9819. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9820. }
  9821. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9822. // Filters
  9823. if (data && generateMipMaps) {
  9824. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9825. }
  9826. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9828. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9829. }
  9830. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9831. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9832. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9833. }
  9834. else {
  9835. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9837. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9838. }
  9839. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9840. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9841. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9842. this._loadedTexturesCache.push(texture);
  9843. return texture;
  9844. };
  9845. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9846. var _this = this;
  9847. if (onLoad === void 0) { onLoad = null; }
  9848. if (onError === void 0) { onError = null; }
  9849. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9850. if (invertY === void 0) { invertY = false; }
  9851. var gl = this._gl;
  9852. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9853. scene._addPendingData(texture);
  9854. texture.url = url;
  9855. var onerror = function () {
  9856. scene._removePendingData(texture);
  9857. if (onError) {
  9858. onError();
  9859. }
  9860. };
  9861. var internalCallback = function (data) {
  9862. var rgbeDataArrays = callback(data);
  9863. var facesIndex = [
  9864. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9865. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9866. ];
  9867. var width = texture._width;
  9868. var height = texture._height;
  9869. if (mipmmapGenerator) {
  9870. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9871. // I ll remove ASAP.
  9872. var textureType = _this._getWebGLTextureType(type);
  9873. var internalFormat = _this._getInternalFormat(format);
  9874. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9875. var needConversion = false;
  9876. if (internalFormat === gl.RGB) {
  9877. internalFormat = gl.RGBA;
  9878. needConversion = true;
  9879. }
  9880. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9881. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9882. var arrayTemp = [];
  9883. // Data are known to be in +X +Y +Z -X -Y -Z
  9884. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9885. arrayTemp.push(rgbeDataArrays[0]); // +X
  9886. arrayTemp.push(rgbeDataArrays[3]); // -X
  9887. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9888. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9889. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9890. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9891. var mipData = mipmmapGenerator(arrayTemp);
  9892. // mipData is order in +X -X +Y -Y +Z -Z
  9893. var mipFaces = [0, 2, 4, 1, 3, 5];
  9894. for (var level = 0; level < mipData.length; level++) {
  9895. var mipSize = width >> level;
  9896. for (var mipIndex in mipFaces) {
  9897. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9898. if (needConversion) {
  9899. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9900. }
  9901. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9902. }
  9903. }
  9904. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9905. }
  9906. else {
  9907. texture.generateMipMaps = !noMipmap;
  9908. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9909. }
  9910. texture.isReady = true;
  9911. _this.resetTextureCache();
  9912. scene._removePendingData(texture);
  9913. if (onLoad) {
  9914. onLoad();
  9915. }
  9916. };
  9917. BABYLON.Tools.LoadFile(url, function (data) {
  9918. internalCallback(data);
  9919. }, onerror, scene.database, true);
  9920. return texture;
  9921. };
  9922. ;
  9923. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9924. // Create new RGBA data container.
  9925. var rgbaData;
  9926. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9927. rgbaData = new Float32Array(width * height * 4);
  9928. }
  9929. else {
  9930. rgbaData = new Uint32Array(width * height * 4);
  9931. }
  9932. // Convert each pixel.
  9933. for (var x = 0; x < width; x++) {
  9934. for (var y = 0; y < height; y++) {
  9935. var index = (y * width + x) * 3;
  9936. var newIndex = (y * width + x) * 4;
  9937. // Map Old Value to new value.
  9938. rgbaData[newIndex + 0] = rgbData[index + 0];
  9939. rgbaData[newIndex + 1] = rgbData[index + 1];
  9940. rgbaData[newIndex + 2] = rgbData[index + 2];
  9941. // Add fully opaque alpha channel.
  9942. rgbaData[newIndex + 3] = 1;
  9943. }
  9944. }
  9945. return rgbaData;
  9946. };
  9947. Engine.prototype._releaseTexture = function (texture) {
  9948. var gl = this._gl;
  9949. if (texture._framebuffer) {
  9950. gl.deleteFramebuffer(texture._framebuffer);
  9951. }
  9952. if (texture._depthStencilBuffer) {
  9953. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9954. }
  9955. if (texture._MSAAFramebuffer) {
  9956. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9957. }
  9958. if (texture._MSAARenderBuffer) {
  9959. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9960. }
  9961. gl.deleteTexture(texture);
  9962. // Unbind channels
  9963. this.unbindAllTextures();
  9964. var index = this._loadedTexturesCache.indexOf(texture);
  9965. if (index !== -1) {
  9966. this._loadedTexturesCache.splice(index, 1);
  9967. }
  9968. };
  9969. Engine.prototype.setProgram = function (program) {
  9970. if (this._currentProgram !== program) {
  9971. this._gl.useProgram(program);
  9972. this._currentProgram = program;
  9973. }
  9974. };
  9975. Engine.prototype.bindSamplers = function (effect) {
  9976. this.setProgram(effect.getProgram());
  9977. var samplers = effect.getSamplers();
  9978. for (var index = 0; index < samplers.length; index++) {
  9979. var uniform = effect.getUniform(samplers[index]);
  9980. this._gl.uniform1i(uniform, index);
  9981. }
  9982. this._currentEffect = null;
  9983. };
  9984. Engine.prototype.activateTexture = function (texture) {
  9985. if (this._activeTexture !== texture) {
  9986. this._gl.activeTexture(texture);
  9987. this._activeTexture = texture;
  9988. }
  9989. };
  9990. Engine.prototype._bindTextureDirectly = function (target, texture) {
  9991. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  9992. this._gl.bindTexture(target, texture);
  9993. this._activeTexturesCache[this._activeTexture] = texture;
  9994. }
  9995. };
  9996. Engine.prototype._bindTexture = function (channel, texture) {
  9997. if (channel < 0) {
  9998. return;
  9999. }
  10000. this.activateTexture(this._gl.TEXTURE0 + channel);
  10001. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10002. };
  10003. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10004. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10005. };
  10006. Engine.prototype.unbindAllTextures = function () {
  10007. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10008. this.activateTexture(this._gl["TEXTURE" + channel]);
  10009. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10010. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10011. }
  10012. };
  10013. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10014. if (channel < 0) {
  10015. return;
  10016. }
  10017. this._gl.uniform1i(uniform, channel);
  10018. this._setTexture(channel, texture);
  10019. };
  10020. Engine.prototype._setTexture = function (channel, texture) {
  10021. // Not ready?
  10022. if (!texture) {
  10023. if (this._activeTexturesCache[channel] != null) {
  10024. this.activateTexture(this._gl["TEXTURE" + channel]);
  10025. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10026. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10027. }
  10028. return;
  10029. }
  10030. // Video
  10031. var alreadyActivated = false;
  10032. if (texture.video) {
  10033. this.activateTexture(this._gl["TEXTURE" + channel]);
  10034. alreadyActivated = true;
  10035. texture.update();
  10036. }
  10037. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10038. texture.delayLoad();
  10039. return;
  10040. }
  10041. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10042. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10043. if (this._activeTexturesCache[channel] === internalTexture) {
  10044. return;
  10045. }
  10046. if (!alreadyActivated) {
  10047. this.activateTexture(this._gl["TEXTURE" + channel]);
  10048. }
  10049. if (internalTexture.isCube) {
  10050. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10051. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10052. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10053. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10054. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10055. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10056. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10057. }
  10058. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10059. }
  10060. else {
  10061. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10062. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10063. internalTexture._cachedWrapU = texture.wrapU;
  10064. switch (texture.wrapU) {
  10065. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10066. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10067. break;
  10068. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10069. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10070. break;
  10071. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10072. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10073. break;
  10074. }
  10075. }
  10076. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10077. internalTexture._cachedWrapV = texture.wrapV;
  10078. switch (texture.wrapV) {
  10079. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10080. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10081. break;
  10082. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10083. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10084. break;
  10085. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10086. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10087. break;
  10088. }
  10089. }
  10090. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10091. }
  10092. };
  10093. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10094. if (channel < 0) {
  10095. return;
  10096. }
  10097. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10098. this._textureUnits = new Int32Array(textures.length);
  10099. }
  10100. for (var i = 0; i < textures.length; i++) {
  10101. this._textureUnits[i] = channel + i;
  10102. }
  10103. this._gl.uniform1iv(uniform, this._textureUnits);
  10104. for (var index = 0; index < textures.length; index++) {
  10105. this._setTexture(channel + index, textures[index]);
  10106. }
  10107. };
  10108. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10109. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10110. var value = texture.anisotropicFilteringLevel;
  10111. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10112. value = 1;
  10113. }
  10114. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10115. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10116. texture._cachedAnisotropicFilteringLevel = value;
  10117. }
  10118. };
  10119. Engine.prototype.readPixels = function (x, y, width, height) {
  10120. var data = new Uint8Array(height * width * 4);
  10121. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10122. return data;
  10123. };
  10124. /**
  10125. * Add an externaly attached data from its key.
  10126. * This method call will fail and return false, if such key already exists.
  10127. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10128. * @param key the unique key that identifies the data
  10129. * @param data the data object to associate to the key for this Engine instance
  10130. * @return true if no such key were already present and the data was added successfully, false otherwise
  10131. */
  10132. Engine.prototype.addExternalData = function (key, data) {
  10133. if (!this._externalData) {
  10134. this._externalData = new BABYLON.StringDictionary();
  10135. }
  10136. return this._externalData.add(key, data);
  10137. };
  10138. /**
  10139. * Get an externaly attached data from its key
  10140. * @param key the unique key that identifies the data
  10141. * @return the associated data, if present (can be null), or undefined if not present
  10142. */
  10143. Engine.prototype.getExternalData = function (key) {
  10144. if (!this._externalData) {
  10145. this._externalData = new BABYLON.StringDictionary();
  10146. }
  10147. return this._externalData.get(key);
  10148. };
  10149. /**
  10150. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10151. * @param key the unique key that identifies the data
  10152. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10153. * @return the associated data, can be null if the factory returned null.
  10154. */
  10155. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10156. if (!this._externalData) {
  10157. this._externalData = new BABYLON.StringDictionary();
  10158. }
  10159. return this._externalData.getOrAddWithFactory(key, factory);
  10160. };
  10161. /**
  10162. * Remove an externaly attached data from the Engine instance
  10163. * @param key the unique key that identifies the data
  10164. * @return true if the data was successfully removed, false if it doesn't exist
  10165. */
  10166. Engine.prototype.removeExternalData = function (key) {
  10167. if (!this._externalData) {
  10168. this._externalData = new BABYLON.StringDictionary();
  10169. }
  10170. return this._externalData.remove(key);
  10171. };
  10172. Engine.prototype.releaseInternalTexture = function (texture) {
  10173. if (!texture) {
  10174. return;
  10175. }
  10176. texture.references--;
  10177. // Final reference ?
  10178. if (texture.references === 0) {
  10179. var texturesCache = this.getLoadedTexturesCache();
  10180. var index = texturesCache.indexOf(texture);
  10181. if (index > -1) {
  10182. texturesCache.splice(index, 1);
  10183. }
  10184. this._releaseTexture(texture);
  10185. }
  10186. };
  10187. Engine.prototype.unbindAllAttributes = function () {
  10188. if (this._mustWipeVertexAttributes) {
  10189. this._mustWipeVertexAttributes = false;
  10190. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10191. this._gl.disableVertexAttribArray(i);
  10192. this._vertexAttribArraysEnabled[i] = false;
  10193. this._currentBufferPointers[i] = null;
  10194. }
  10195. return;
  10196. }
  10197. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10198. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10199. continue;
  10200. }
  10201. this._gl.disableVertexAttribArray(i);
  10202. this._vertexAttribArraysEnabled[i] = false;
  10203. this._currentBufferPointers[i] = null;
  10204. }
  10205. };
  10206. Engine.prototype.releaseEffects = function () {
  10207. for (var name in this._compiledEffects) {
  10208. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10209. }
  10210. this._compiledEffects = {};
  10211. };
  10212. // Dispose
  10213. Engine.prototype.dispose = function () {
  10214. this.hideLoadingUI();
  10215. this.stopRenderLoop();
  10216. // Empty texture
  10217. if (this._emptyTexture) {
  10218. this._releaseTexture(this._emptyTexture);
  10219. this._emptyTexture = null;
  10220. }
  10221. if (this._emptyCubeTexture) {
  10222. this._releaseTexture(this._emptyCubeTexture);
  10223. this._emptyCubeTexture = null;
  10224. }
  10225. // Release scenes
  10226. while (this.scenes.length) {
  10227. this.scenes[0].dispose();
  10228. }
  10229. // Release audio engine
  10230. if (Engine.audioEngine) {
  10231. Engine.audioEngine.dispose();
  10232. }
  10233. // Release effects
  10234. this.releaseEffects();
  10235. // Unbind
  10236. this.unbindAllAttributes();
  10237. this._gl = null;
  10238. //WebVR
  10239. this.disableVR();
  10240. // Events
  10241. window.removeEventListener("blur", this._onBlur);
  10242. window.removeEventListener("focus", this._onFocus);
  10243. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10244. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10245. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10246. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10247. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10248. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10249. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10250. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10251. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10252. // Remove from Instances
  10253. var index = Engine.Instances.indexOf(this);
  10254. if (index >= 0) {
  10255. Engine.Instances.splice(index, 1);
  10256. }
  10257. };
  10258. // Loading screen
  10259. Engine.prototype.displayLoadingUI = function () {
  10260. var loadingScreen = this.loadingScreen;
  10261. if (loadingScreen) {
  10262. loadingScreen.displayLoadingUI();
  10263. }
  10264. };
  10265. Engine.prototype.hideLoadingUI = function () {
  10266. var loadingScreen = this.loadingScreen;
  10267. if (loadingScreen) {
  10268. loadingScreen.hideLoadingUI();
  10269. }
  10270. };
  10271. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10272. get: function () {
  10273. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10274. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10275. return this._loadingScreen;
  10276. },
  10277. set: function (loadingScreen) {
  10278. this._loadingScreen = loadingScreen;
  10279. },
  10280. enumerable: true,
  10281. configurable: true
  10282. });
  10283. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10284. set: function (text) {
  10285. this.loadingScreen.loadingUIText = text;
  10286. },
  10287. enumerable: true,
  10288. configurable: true
  10289. });
  10290. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10291. set: function (color) {
  10292. this.loadingScreen.loadingUIBackgroundColor = color;
  10293. },
  10294. enumerable: true,
  10295. configurable: true
  10296. });
  10297. Engine.prototype.attachContextLostEvent = function (callback) {
  10298. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10299. };
  10300. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10301. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10302. };
  10303. Engine.prototype.getVertexShaderSource = function (program) {
  10304. var shaders = this._gl.getAttachedShaders(program);
  10305. return this._gl.getShaderSource(shaders[0]);
  10306. };
  10307. Engine.prototype.getFragmentShaderSource = function (program) {
  10308. var shaders = this._gl.getAttachedShaders(program);
  10309. return this._gl.getShaderSource(shaders[1]);
  10310. };
  10311. // FPS
  10312. Engine.prototype.getFps = function () {
  10313. return this.fps;
  10314. };
  10315. Engine.prototype.getDeltaTime = function () {
  10316. return this.deltaTime;
  10317. };
  10318. Engine.prototype._measureFps = function () {
  10319. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10320. var length = this.previousFramesDuration.length;
  10321. if (length >= 2) {
  10322. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10323. }
  10324. if (length >= this.fpsRange) {
  10325. if (length > this.fpsRange) {
  10326. this.previousFramesDuration.splice(0, 1);
  10327. length = this.previousFramesDuration.length;
  10328. }
  10329. var sum = 0;
  10330. for (var id = 0; id < length - 1; id++) {
  10331. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10332. }
  10333. this.fps = 1000.0 / (sum / (length - 1));
  10334. }
  10335. };
  10336. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10337. if (this._webGLVersion > 1) {
  10338. return this._caps.colorBufferFloat;
  10339. }
  10340. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10341. };
  10342. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10343. if (this._webGLVersion > 1) {
  10344. return this._caps.colorBufferFloat;
  10345. }
  10346. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10347. };
  10348. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10349. Engine.prototype._canRenderToFramebuffer = function (type) {
  10350. var gl = this._gl;
  10351. //clear existing errors
  10352. while (gl.getError() !== gl.NO_ERROR) { }
  10353. var successful = true;
  10354. var texture = gl.createTexture();
  10355. gl.bindTexture(gl.TEXTURE_2D, texture);
  10356. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10357. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10358. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10359. var fb = gl.createFramebuffer();
  10360. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10361. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10362. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10363. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10364. successful = successful && (gl.getError() === gl.NO_ERROR);
  10365. //try render by clearing frame buffer's color buffer
  10366. if (successful) {
  10367. gl.clear(gl.COLOR_BUFFER_BIT);
  10368. successful = successful && (gl.getError() === gl.NO_ERROR);
  10369. }
  10370. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10371. if (successful) {
  10372. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10373. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10374. var readFormat = gl.RGBA;
  10375. var readType = gl.UNSIGNED_BYTE;
  10376. var buffer = new Uint8Array(4);
  10377. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10378. successful = successful && (gl.getError() === gl.NO_ERROR);
  10379. }
  10380. //clean up
  10381. gl.deleteTexture(texture);
  10382. gl.deleteFramebuffer(fb);
  10383. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10384. //clear accumulated errors
  10385. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10386. return successful;
  10387. };
  10388. Engine.prototype._getWebGLTextureType = function (type) {
  10389. if (type === Engine.TEXTURETYPE_FLOAT) {
  10390. return this._gl.FLOAT;
  10391. }
  10392. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10393. // Add Half Float Constant.
  10394. return Engine.HALF_FLOAT_OES;
  10395. }
  10396. return this._gl.UNSIGNED_BYTE;
  10397. };
  10398. ;
  10399. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10400. if (this._webGLVersion === 1) {
  10401. return this._gl.RGBA;
  10402. }
  10403. if (type === Engine.TEXTURETYPE_FLOAT) {
  10404. return Engine.RGBA32F;
  10405. }
  10406. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10407. return Engine.RGBA16F;
  10408. }
  10409. return this._gl.RGBA;
  10410. };
  10411. ;
  10412. // Statics
  10413. Engine.isSupported = function () {
  10414. try {
  10415. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10416. if (navigator.isCocoonJS) {
  10417. return true;
  10418. }
  10419. var tempcanvas = document.createElement("canvas");
  10420. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10421. return gl != null && !!window.WebGLRenderingContext;
  10422. }
  10423. catch (e) {
  10424. return false;
  10425. }
  10426. };
  10427. return Engine;
  10428. }());
  10429. Engine.Instances = new Array();
  10430. // Const statics
  10431. Engine._ALPHA_DISABLE = 0;
  10432. Engine._ALPHA_ADD = 1;
  10433. Engine._ALPHA_COMBINE = 2;
  10434. Engine._ALPHA_SUBTRACT = 3;
  10435. Engine._ALPHA_MULTIPLY = 4;
  10436. Engine._ALPHA_MAXIMIZED = 5;
  10437. Engine._ALPHA_ONEONE = 6;
  10438. Engine._ALPHA_PREMULTIPLIED = 7;
  10439. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10440. Engine._ALPHA_INTERPOLATE = 9;
  10441. Engine._ALPHA_SCREENMODE = 10;
  10442. Engine._DELAYLOADSTATE_NONE = 0;
  10443. Engine._DELAYLOADSTATE_LOADED = 1;
  10444. Engine._DELAYLOADSTATE_LOADING = 2;
  10445. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10446. Engine._TEXTUREFORMAT_ALPHA = 0;
  10447. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10448. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10449. Engine._TEXTUREFORMAT_RGB = 4;
  10450. Engine._TEXTUREFORMAT_RGBA = 5;
  10451. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10452. Engine._TEXTURETYPE_FLOAT = 1;
  10453. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10454. // Depht or Stencil test Constants.
  10455. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10456. 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.
  10457. 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.
  10458. 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.
  10459. 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.
  10460. 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.
  10461. 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.
  10462. 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.
  10463. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10464. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10465. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10466. // Stencil Actions Constants.
  10467. Engine._KEEP = 0x1E00;
  10468. Engine._REPLACE = 0x1E01;
  10469. Engine._INCR = 0x1E02;
  10470. Engine._DECR = 0x1E03;
  10471. Engine._INVERT = 0x150A;
  10472. Engine._INCR_WRAP = 0x8507;
  10473. Engine._DECR_WRAP = 0x8508;
  10474. // Texture rescaling mode
  10475. Engine._SCALEMODE_FLOOR = 1;
  10476. Engine._SCALEMODE_NEAREST = 2;
  10477. Engine._SCALEMODE_CEILING = 3;
  10478. // Updatable statics so stick with vars here
  10479. Engine.CollisionsEpsilon = 0.001;
  10480. Engine.CodeRepository = "src/";
  10481. Engine.ShadersRepository = "src/Shaders/";
  10482. BABYLON.Engine = Engine;
  10483. })(BABYLON || (BABYLON = {}));
  10484. //# sourceMappingURL=babylon.engine.js.map
  10485. /// <reference path="Tools\babylon.decorators.ts" />
  10486. var BABYLON;
  10487. (function (BABYLON) {
  10488. /**
  10489. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10490. */
  10491. var Node = (function () {
  10492. /**
  10493. * @constructor
  10494. * @param {string} name - the name and id to be given to this node
  10495. * @param {BABYLON.Scene} the scene this node will be added to
  10496. */
  10497. function Node(name, scene) {
  10498. this.state = "";
  10499. this.metadata = null;
  10500. this.doNotSerialize = false;
  10501. this.animations = new Array();
  10502. this._ranges = {};
  10503. this._childrenFlag = -1;
  10504. this._isEnabled = true;
  10505. this._isReady = true;
  10506. this._currentRenderId = -1;
  10507. this._parentRenderId = -1;
  10508. /**
  10509. * An event triggered when the mesh is disposed.
  10510. * @type {BABYLON.Observable}
  10511. */
  10512. this.onDisposeObservable = new BABYLON.Observable();
  10513. this.name = name;
  10514. this.id = name;
  10515. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10516. this._initCache();
  10517. }
  10518. Object.defineProperty(Node.prototype, "parent", {
  10519. get: function () {
  10520. return this._parentNode;
  10521. },
  10522. set: function (parent) {
  10523. if (this._parentNode === parent) {
  10524. return;
  10525. }
  10526. if (this._parentNode) {
  10527. var index = this._parentNode._children.indexOf(this);
  10528. if (index !== -1) {
  10529. this._parentNode._children.splice(index, 1);
  10530. }
  10531. }
  10532. this._parentNode = parent;
  10533. if (this._parentNode) {
  10534. if (!this._parentNode._children) {
  10535. this._parentNode._children = new Array();
  10536. }
  10537. this._parentNode._children.push(this);
  10538. }
  10539. },
  10540. enumerable: true,
  10541. configurable: true
  10542. });
  10543. Node.prototype.getClassName = function () {
  10544. return "Node";
  10545. };
  10546. Object.defineProperty(Node.prototype, "onDispose", {
  10547. set: function (callback) {
  10548. if (this._onDisposeObserver) {
  10549. this.onDisposeObservable.remove(this._onDisposeObserver);
  10550. }
  10551. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10552. },
  10553. enumerable: true,
  10554. configurable: true
  10555. });
  10556. Node.prototype.getScene = function () {
  10557. return this._scene;
  10558. };
  10559. Node.prototype.getEngine = function () {
  10560. return this._scene.getEngine();
  10561. };
  10562. // override it in derived class
  10563. Node.prototype.getWorldMatrix = function () {
  10564. return BABYLON.Matrix.Identity();
  10565. };
  10566. // override it in derived class if you add new variables to the cache
  10567. // and call the parent class method
  10568. Node.prototype._initCache = function () {
  10569. this._cache = {};
  10570. this._cache.parent = undefined;
  10571. };
  10572. Node.prototype.updateCache = function (force) {
  10573. if (!force && this.isSynchronized())
  10574. return;
  10575. this._cache.parent = this.parent;
  10576. this._updateCache();
  10577. };
  10578. // override it in derived class if you add new variables to the cache
  10579. // and call the parent class method if !ignoreParentClass
  10580. Node.prototype._updateCache = function (ignoreParentClass) {
  10581. };
  10582. // override it in derived class if you add new variables to the cache
  10583. Node.prototype._isSynchronized = function () {
  10584. return true;
  10585. };
  10586. Node.prototype._markSyncedWithParent = function () {
  10587. this._parentRenderId = this.parent._currentRenderId;
  10588. };
  10589. Node.prototype.isSynchronizedWithParent = function () {
  10590. if (!this.parent) {
  10591. return true;
  10592. }
  10593. if (this._parentRenderId !== this.parent._currentRenderId) {
  10594. return false;
  10595. }
  10596. return this.parent.isSynchronized();
  10597. };
  10598. Node.prototype.isSynchronized = function (updateCache) {
  10599. var check = this.hasNewParent();
  10600. check = check || !this.isSynchronizedWithParent();
  10601. check = check || !this._isSynchronized();
  10602. if (updateCache)
  10603. this.updateCache(true);
  10604. return !check;
  10605. };
  10606. Node.prototype.hasNewParent = function (update) {
  10607. if (this._cache.parent === this.parent)
  10608. return false;
  10609. if (update)
  10610. this._cache.parent = this.parent;
  10611. return true;
  10612. };
  10613. /**
  10614. * Is this node ready to be used/rendered
  10615. * @return {boolean} is it ready
  10616. */
  10617. Node.prototype.isReady = function () {
  10618. return this._isReady;
  10619. };
  10620. /**
  10621. * Is this node enabled.
  10622. * If the node has a parent and is enabled, the parent will be inspected as well.
  10623. * @return {boolean} whether this node (and its parent) is enabled.
  10624. * @see setEnabled
  10625. */
  10626. Node.prototype.isEnabled = function () {
  10627. if (!this._isEnabled) {
  10628. return false;
  10629. }
  10630. if (this.parent) {
  10631. return this.parent.isEnabled();
  10632. }
  10633. return true;
  10634. };
  10635. /**
  10636. * Set the enabled state of this node.
  10637. * @param {boolean} value - the new enabled state
  10638. * @see isEnabled
  10639. */
  10640. Node.prototype.setEnabled = function (value) {
  10641. this._isEnabled = value;
  10642. };
  10643. /**
  10644. * Is this node a descendant of the given node.
  10645. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10646. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10647. * @see parent
  10648. */
  10649. Node.prototype.isDescendantOf = function (ancestor) {
  10650. if (this.parent) {
  10651. if (this.parent === ancestor) {
  10652. return true;
  10653. }
  10654. return this.parent.isDescendantOf(ancestor);
  10655. }
  10656. return false;
  10657. };
  10658. /**
  10659. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10660. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10661. * @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.
  10662. * @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.
  10663. */
  10664. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10665. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10666. if (!this._children) {
  10667. return;
  10668. }
  10669. for (var index = 0; index < this._children.length; index++) {
  10670. var item = this._children[index];
  10671. if (!predicate || predicate(item)) {
  10672. results.push(item);
  10673. }
  10674. if (!directDescendantsOnly) {
  10675. item._getDescendants(results, false, predicate);
  10676. }
  10677. }
  10678. };
  10679. /**
  10680. * Will return all nodes that have this node as ascendant.
  10681. * @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.
  10682. * @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.
  10683. * @return {BABYLON.Node[]} all children nodes of all types.
  10684. */
  10685. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10686. var results = [];
  10687. this._getDescendants(results, directDescendantsOnly, predicate);
  10688. return results;
  10689. };
  10690. /**
  10691. * Get all child-meshes of this node.
  10692. */
  10693. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10694. var results = [];
  10695. this._getDescendants(results, directDecendantsOnly, function (node) {
  10696. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10697. });
  10698. return results;
  10699. };
  10700. /**
  10701. * Get all direct children of this node.
  10702. */
  10703. Node.prototype.getChildren = function (predicate) {
  10704. return this.getDescendants(true, predicate);
  10705. };
  10706. Node.prototype._setReady = function (state) {
  10707. if (state === this._isReady) {
  10708. return;
  10709. }
  10710. if (!state) {
  10711. this._isReady = false;
  10712. return;
  10713. }
  10714. this._isReady = true;
  10715. if (this.onReady) {
  10716. this.onReady(this);
  10717. }
  10718. };
  10719. Node.prototype.getAnimationByName = function (name) {
  10720. for (var i = 0; i < this.animations.length; i++) {
  10721. var animation = this.animations[i];
  10722. if (animation.name === name) {
  10723. return animation;
  10724. }
  10725. }
  10726. return null;
  10727. };
  10728. Node.prototype.createAnimationRange = function (name, from, to) {
  10729. // check name not already in use
  10730. if (!this._ranges[name]) {
  10731. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10732. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10733. if (this.animations[i]) {
  10734. this.animations[i].createRange(name, from, to);
  10735. }
  10736. }
  10737. }
  10738. };
  10739. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10740. if (deleteFrames === void 0) { deleteFrames = true; }
  10741. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10742. if (this.animations[i]) {
  10743. this.animations[i].deleteRange(name, deleteFrames);
  10744. }
  10745. }
  10746. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10747. };
  10748. Node.prototype.getAnimationRange = function (name) {
  10749. return this._ranges[name];
  10750. };
  10751. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10752. var range = this.getAnimationRange(name);
  10753. if (!range) {
  10754. return null;
  10755. }
  10756. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10757. };
  10758. Node.prototype.serializeAnimationRanges = function () {
  10759. var serializationRanges = [];
  10760. for (var name in this._ranges) {
  10761. var range = {};
  10762. range.name = name;
  10763. range.from = this._ranges[name].from;
  10764. range.to = this._ranges[name].to;
  10765. serializationRanges.push(range);
  10766. }
  10767. return serializationRanges;
  10768. };
  10769. Node.prototype.dispose = function () {
  10770. this.parent = null;
  10771. // Callback
  10772. this.onDisposeObservable.notifyObservers(this);
  10773. this.onDisposeObservable.clear();
  10774. };
  10775. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10776. if (parsedNode.ranges) {
  10777. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10778. var data = parsedNode.ranges[index];
  10779. node.createAnimationRange(data.name, data.from, data.to);
  10780. }
  10781. }
  10782. };
  10783. return Node;
  10784. }());
  10785. __decorate([
  10786. BABYLON.serialize()
  10787. ], Node.prototype, "name", void 0);
  10788. __decorate([
  10789. BABYLON.serialize()
  10790. ], Node.prototype, "id", void 0);
  10791. __decorate([
  10792. BABYLON.serialize()
  10793. ], Node.prototype, "uniqueId", void 0);
  10794. __decorate([
  10795. BABYLON.serialize()
  10796. ], Node.prototype, "state", void 0);
  10797. __decorate([
  10798. BABYLON.serialize()
  10799. ], Node.prototype, "metadata", void 0);
  10800. BABYLON.Node = Node;
  10801. })(BABYLON || (BABYLON = {}));
  10802. //# sourceMappingURL=babylon.node.js.map
  10803. var BABYLON;
  10804. (function (BABYLON) {
  10805. var BoundingSphere = (function () {
  10806. function BoundingSphere(minimum, maximum) {
  10807. this.minimum = minimum;
  10808. this.maximum = maximum;
  10809. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10810. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10811. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10812. this.radius = distance * 0.5;
  10813. this.centerWorld = BABYLON.Vector3.Zero();
  10814. this._update(BABYLON.Matrix.Identity());
  10815. }
  10816. // Methods
  10817. BoundingSphere.prototype._update = function (world) {
  10818. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10819. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10820. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10821. };
  10822. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10823. for (var i = 0; i < 6; i++) {
  10824. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10825. return false;
  10826. }
  10827. return true;
  10828. };
  10829. BoundingSphere.prototype.intersectsPoint = function (point) {
  10830. var x = this.centerWorld.x - point.x;
  10831. var y = this.centerWorld.y - point.y;
  10832. var z = this.centerWorld.z - point.z;
  10833. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10834. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10835. return false;
  10836. return true;
  10837. };
  10838. // Statics
  10839. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10840. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10841. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10842. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10843. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10844. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10845. return false;
  10846. return true;
  10847. };
  10848. return BoundingSphere;
  10849. }());
  10850. BABYLON.BoundingSphere = BoundingSphere;
  10851. })(BABYLON || (BABYLON = {}));
  10852. //# sourceMappingURL=babylon.boundingSphere.js.map
  10853. var BABYLON;
  10854. (function (BABYLON) {
  10855. var BoundingBox = (function () {
  10856. function BoundingBox(minimum, maximum) {
  10857. this.minimum = minimum;
  10858. this.maximum = maximum;
  10859. this.vectors = new Array();
  10860. this.vectorsWorld = new Array();
  10861. // Bounding vectors
  10862. this.vectors.push(this.minimum.clone());
  10863. this.vectors.push(this.maximum.clone());
  10864. this.vectors.push(this.minimum.clone());
  10865. this.vectors[2].x = this.maximum.x;
  10866. this.vectors.push(this.minimum.clone());
  10867. this.vectors[3].y = this.maximum.y;
  10868. this.vectors.push(this.minimum.clone());
  10869. this.vectors[4].z = this.maximum.z;
  10870. this.vectors.push(this.maximum.clone());
  10871. this.vectors[5].z = this.minimum.z;
  10872. this.vectors.push(this.maximum.clone());
  10873. this.vectors[6].x = this.minimum.x;
  10874. this.vectors.push(this.maximum.clone());
  10875. this.vectors[7].y = this.minimum.y;
  10876. // OBB
  10877. this.center = this.maximum.add(this.minimum).scale(0.5);
  10878. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10879. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10880. // World
  10881. for (var index = 0; index < this.vectors.length; index++) {
  10882. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10883. }
  10884. this.minimumWorld = BABYLON.Vector3.Zero();
  10885. this.maximumWorld = BABYLON.Vector3.Zero();
  10886. this.centerWorld = BABYLON.Vector3.Zero();
  10887. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10888. this._update(BABYLON.Matrix.Identity());
  10889. }
  10890. // Methods
  10891. BoundingBox.prototype.getWorldMatrix = function () {
  10892. return this._worldMatrix;
  10893. };
  10894. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10895. this._worldMatrix.copyFrom(matrix);
  10896. return this;
  10897. };
  10898. BoundingBox.prototype._update = function (world) {
  10899. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10900. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10901. for (var index = 0; index < this.vectors.length; index++) {
  10902. var v = this.vectorsWorld[index];
  10903. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10904. if (v.x < this.minimumWorld.x)
  10905. this.minimumWorld.x = v.x;
  10906. if (v.y < this.minimumWorld.y)
  10907. this.minimumWorld.y = v.y;
  10908. if (v.z < this.minimumWorld.z)
  10909. this.minimumWorld.z = v.z;
  10910. if (v.x > this.maximumWorld.x)
  10911. this.maximumWorld.x = v.x;
  10912. if (v.y > this.maximumWorld.y)
  10913. this.maximumWorld.y = v.y;
  10914. if (v.z > this.maximumWorld.z)
  10915. this.maximumWorld.z = v.z;
  10916. }
  10917. // Extend
  10918. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10919. this.extendSizeWorld.scaleInPlace(0.5);
  10920. // OBB
  10921. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10922. this.centerWorld.scaleInPlace(0.5);
  10923. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10924. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10925. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10926. this._worldMatrix = world;
  10927. };
  10928. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10929. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10930. };
  10931. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10932. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10933. };
  10934. BoundingBox.prototype.intersectsPoint = function (point) {
  10935. var delta = -BABYLON.Epsilon;
  10936. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10937. return false;
  10938. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10939. return false;
  10940. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10941. return false;
  10942. return true;
  10943. };
  10944. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10945. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10946. };
  10947. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10948. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10949. return false;
  10950. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10951. return false;
  10952. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10953. return false;
  10954. return true;
  10955. };
  10956. // Statics
  10957. BoundingBox.Intersects = function (box0, box1) {
  10958. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10959. return false;
  10960. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10961. return false;
  10962. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10963. return false;
  10964. return true;
  10965. };
  10966. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10967. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10968. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10969. return (num <= (sphereRadius * sphereRadius));
  10970. };
  10971. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10972. for (var p = 0; p < 6; p++) {
  10973. for (var i = 0; i < 8; i++) {
  10974. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10975. return false;
  10976. }
  10977. }
  10978. }
  10979. return true;
  10980. };
  10981. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10982. for (var p = 0; p < 6; p++) {
  10983. var inCount = 8;
  10984. for (var i = 0; i < 8; i++) {
  10985. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10986. --inCount;
  10987. }
  10988. else {
  10989. break;
  10990. }
  10991. }
  10992. if (inCount === 0)
  10993. return false;
  10994. }
  10995. return true;
  10996. };
  10997. return BoundingBox;
  10998. }());
  10999. BABYLON.BoundingBox = BoundingBox;
  11000. })(BABYLON || (BABYLON = {}));
  11001. //# sourceMappingURL=babylon.boundingBox.js.map
  11002. var BABYLON;
  11003. (function (BABYLON) {
  11004. var computeBoxExtents = function (axis, box) {
  11005. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11006. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11007. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11008. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11009. var r = r0 + r1 + r2;
  11010. return {
  11011. min: p - r,
  11012. max: p + r
  11013. };
  11014. };
  11015. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11016. var axisOverlap = function (axis, box0, box1) {
  11017. var result0 = computeBoxExtents(axis, box0);
  11018. var result1 = computeBoxExtents(axis, box1);
  11019. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11020. };
  11021. var BoundingInfo = (function () {
  11022. function BoundingInfo(minimum, maximum) {
  11023. this.minimum = minimum;
  11024. this.maximum = maximum;
  11025. this._isLocked = false;
  11026. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11027. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11028. }
  11029. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11030. get: function () {
  11031. return this._isLocked;
  11032. },
  11033. set: function (value) {
  11034. this._isLocked = value;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. // Methods
  11040. BoundingInfo.prototype.update = function (world) {
  11041. if (this._isLocked) {
  11042. return;
  11043. }
  11044. this.boundingBox._update(world);
  11045. this.boundingSphere._update(world);
  11046. };
  11047. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11048. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11049. return false;
  11050. return this.boundingBox.isInFrustum(frustumPlanes);
  11051. };
  11052. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11053. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11054. };
  11055. BoundingInfo.prototype._checkCollision = function (collider) {
  11056. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11057. };
  11058. BoundingInfo.prototype.intersectsPoint = function (point) {
  11059. if (!this.boundingSphere.centerWorld) {
  11060. return false;
  11061. }
  11062. if (!this.boundingSphere.intersectsPoint(point)) {
  11063. return false;
  11064. }
  11065. if (!this.boundingBox.intersectsPoint(point)) {
  11066. return false;
  11067. }
  11068. return true;
  11069. };
  11070. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11071. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11072. return false;
  11073. }
  11074. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11075. return false;
  11076. }
  11077. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11078. return false;
  11079. }
  11080. if (!precise) {
  11081. return true;
  11082. }
  11083. var box0 = this.boundingBox;
  11084. var box1 = boundingInfo.boundingBox;
  11085. if (!axisOverlap(box0.directions[0], box0, box1))
  11086. return false;
  11087. if (!axisOverlap(box0.directions[1], box0, box1))
  11088. return false;
  11089. if (!axisOverlap(box0.directions[2], box0, box1))
  11090. return false;
  11091. if (!axisOverlap(box1.directions[0], box0, box1))
  11092. return false;
  11093. if (!axisOverlap(box1.directions[1], box0, box1))
  11094. return false;
  11095. if (!axisOverlap(box1.directions[2], box0, box1))
  11096. return false;
  11097. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11098. return false;
  11099. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11100. return false;
  11101. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11102. return false;
  11103. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11104. return false;
  11105. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11106. return false;
  11107. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11108. return false;
  11109. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11110. return false;
  11111. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11112. return false;
  11113. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11114. return false;
  11115. return true;
  11116. };
  11117. return BoundingInfo;
  11118. }());
  11119. BABYLON.BoundingInfo = BoundingInfo;
  11120. })(BABYLON || (BABYLON = {}));
  11121. //# sourceMappingURL=babylon.boundingInfo.js.map
  11122. var BABYLON;
  11123. (function (BABYLON) {
  11124. var AbstractMesh = (function (_super) {
  11125. __extends(AbstractMesh, _super);
  11126. // Constructor
  11127. function AbstractMesh(name, scene) {
  11128. var _this = _super.call(this, name, scene) || this;
  11129. _this._facetNb = 0; // facet number
  11130. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11131. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11132. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11133. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11134. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11135. _this._subDiv = {
  11136. max: 1,
  11137. X: 1,
  11138. Y: 1,
  11139. Z: 1
  11140. };
  11141. // Events
  11142. /**
  11143. * An event triggered when this mesh collides with another one
  11144. * @type {BABYLON.Observable}
  11145. */
  11146. _this.onCollideObservable = new BABYLON.Observable();
  11147. /**
  11148. * An event triggered when the collision's position changes
  11149. * @type {BABYLON.Observable}
  11150. */
  11151. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11152. /**
  11153. * An event triggered after the world matrix is updated
  11154. * @type {BABYLON.Observable}
  11155. */
  11156. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11157. // Properties
  11158. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11159. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11160. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11161. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  11162. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11163. _this.visibility = 1.0;
  11164. _this.alphaIndex = Number.MAX_VALUE;
  11165. _this.infiniteDistance = false;
  11166. _this.isVisible = true;
  11167. _this.isPickable = true;
  11168. _this.showBoundingBox = false;
  11169. _this.showSubMeshesBoundingBox = false;
  11170. _this.isBlocker = false;
  11171. _this.renderingGroupId = 0;
  11172. _this._receiveShadows = false;
  11173. _this.renderOutline = false;
  11174. _this.outlineColor = BABYLON.Color3.Red();
  11175. _this.outlineWidth = 0.02;
  11176. _this.renderOverlay = false;
  11177. _this.overlayColor = BABYLON.Color3.Red();
  11178. _this.overlayAlpha = 0.5;
  11179. _this._hasVertexAlpha = false;
  11180. _this._useVertexColors = true;
  11181. _this._computeBonesUsingShaders = true;
  11182. _this._numBoneInfluencers = 4;
  11183. _this._applyFog = true;
  11184. _this.scalingDeterminant = 1;
  11185. _this.useOctreeForRenderingSelection = true;
  11186. _this.useOctreeForPicking = true;
  11187. _this.useOctreeForCollisions = true;
  11188. _this.layerMask = 0x0FFFFFFF;
  11189. /**
  11190. * True if the mesh must be rendered in any case.
  11191. */
  11192. _this.alwaysSelectAsActiveMesh = false;
  11193. // Collisions
  11194. _this._checkCollisions = false;
  11195. _this._collisionMask = -1;
  11196. _this._collisionGroup = -1;
  11197. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11198. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11199. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11200. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11201. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11202. // Edges
  11203. _this.edgesWidth = 1;
  11204. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11205. // Cache
  11206. _this._localWorld = BABYLON.Matrix.Zero();
  11207. _this._worldMatrix = BABYLON.Matrix.Zero();
  11208. _this._absolutePosition = BABYLON.Vector3.Zero();
  11209. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11210. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11211. _this._isDirty = false;
  11212. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11213. _this._isDisposed = false;
  11214. _this._renderId = 0;
  11215. _this._intersectionsInProgress = new Array();
  11216. _this._isWorldMatrixFrozen = false;
  11217. _this._unIndexed = false;
  11218. _this._lightSources = new Array();
  11219. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11220. if (collidedMesh === void 0) { collidedMesh = null; }
  11221. //TODO move this to the collision coordinator!
  11222. if (_this.getScene().workerCollisions)
  11223. newPosition.multiplyInPlace(_this._collider.radius);
  11224. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11225. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11226. _this.position.addInPlace(_this._diffPositionForCollisions);
  11227. }
  11228. if (collidedMesh) {
  11229. _this.onCollideObservable.notifyObservers(collidedMesh);
  11230. }
  11231. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11232. };
  11233. _this.getScene().addMesh(_this);
  11234. _this._resyncLightSources();
  11235. return _this;
  11236. }
  11237. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11238. get: function () {
  11239. return AbstractMesh._BILLBOARDMODE_NONE;
  11240. },
  11241. enumerable: true,
  11242. configurable: true
  11243. });
  11244. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11245. get: function () {
  11246. return AbstractMesh._BILLBOARDMODE_X;
  11247. },
  11248. enumerable: true,
  11249. configurable: true
  11250. });
  11251. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11252. get: function () {
  11253. return AbstractMesh._BILLBOARDMODE_Y;
  11254. },
  11255. enumerable: true,
  11256. configurable: true
  11257. });
  11258. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11259. get: function () {
  11260. return AbstractMesh._BILLBOARDMODE_Z;
  11261. },
  11262. enumerable: true,
  11263. configurable: true
  11264. });
  11265. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11266. get: function () {
  11267. return AbstractMesh._BILLBOARDMODE_ALL;
  11268. },
  11269. enumerable: true,
  11270. configurable: true
  11271. });
  11272. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11273. /**
  11274. * Read-only : the number of facets in the mesh
  11275. */
  11276. get: function () {
  11277. return this._facetNb;
  11278. },
  11279. enumerable: true,
  11280. configurable: true
  11281. });
  11282. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11283. /**
  11284. * The number (integer) of subdivisions per axis in the partioning space
  11285. */
  11286. get: function () {
  11287. return this._partitioningSubdivisions;
  11288. },
  11289. set: function (nb) {
  11290. this._partitioningSubdivisions = nb;
  11291. },
  11292. enumerable: true,
  11293. configurable: true
  11294. });
  11295. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11296. /**
  11297. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11298. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11299. */
  11300. get: function () {
  11301. return this._partitioningBBoxRatio;
  11302. },
  11303. set: function (ratio) {
  11304. this._partitioningBBoxRatio = ratio;
  11305. },
  11306. enumerable: true,
  11307. configurable: true
  11308. });
  11309. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11310. /**
  11311. * Read-only boolean : is the feature facetData enabled ?
  11312. */
  11313. get: function () {
  11314. return this._facetDataEnabled;
  11315. },
  11316. enumerable: true,
  11317. configurable: true
  11318. });
  11319. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11320. set: function (callback) {
  11321. if (this._onCollideObserver) {
  11322. this.onCollideObservable.remove(this._onCollideObserver);
  11323. }
  11324. this._onCollideObserver = this.onCollideObservable.add(callback);
  11325. },
  11326. enumerable: true,
  11327. configurable: true
  11328. });
  11329. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11330. set: function (callback) {
  11331. if (this._onCollisionPositionChangeObserver) {
  11332. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11333. }
  11334. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11335. },
  11336. enumerable: true,
  11337. configurable: true
  11338. });
  11339. Object.defineProperty(AbstractMesh.prototype, "material", {
  11340. get: function () {
  11341. return this._material;
  11342. },
  11343. set: function (value) {
  11344. if (this._material === value) {
  11345. return;
  11346. }
  11347. this._material = value;
  11348. if (!this.subMeshes) {
  11349. return;
  11350. }
  11351. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11352. var subMesh = _a[_i];
  11353. subMesh.setEffect(null);
  11354. }
  11355. },
  11356. enumerable: true,
  11357. configurable: true
  11358. });
  11359. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11360. get: function () {
  11361. return this._receiveShadows;
  11362. },
  11363. set: function (value) {
  11364. if (this._receiveShadows === value) {
  11365. return;
  11366. }
  11367. this._receiveShadows = value;
  11368. this._markSubMeshesAsLightDirty();
  11369. },
  11370. enumerable: true,
  11371. configurable: true
  11372. });
  11373. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11374. get: function () {
  11375. return this._hasVertexAlpha;
  11376. },
  11377. set: function (value) {
  11378. if (this._hasVertexAlpha === value) {
  11379. return;
  11380. }
  11381. this._hasVertexAlpha = value;
  11382. this._markSubMeshesAsAttributesDirty();
  11383. },
  11384. enumerable: true,
  11385. configurable: true
  11386. });
  11387. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11388. get: function () {
  11389. return this._useVertexColors;
  11390. },
  11391. set: function (value) {
  11392. if (this._useVertexColors === value) {
  11393. return;
  11394. }
  11395. this._useVertexColors = value;
  11396. this._markSubMeshesAsAttributesDirty();
  11397. },
  11398. enumerable: true,
  11399. configurable: true
  11400. });
  11401. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11402. get: function () {
  11403. return this._computeBonesUsingShaders;
  11404. },
  11405. set: function (value) {
  11406. if (this._computeBonesUsingShaders === value) {
  11407. return;
  11408. }
  11409. this._computeBonesUsingShaders = value;
  11410. this._markSubMeshesAsAttributesDirty();
  11411. },
  11412. enumerable: true,
  11413. configurable: true
  11414. });
  11415. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11416. get: function () {
  11417. return this._numBoneInfluencers;
  11418. },
  11419. set: function (value) {
  11420. if (this._numBoneInfluencers === value) {
  11421. return;
  11422. }
  11423. this._numBoneInfluencers = value;
  11424. this._markSubMeshesAsAttributesDirty();
  11425. },
  11426. enumerable: true,
  11427. configurable: true
  11428. });
  11429. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11430. get: function () {
  11431. return this._applyFog;
  11432. },
  11433. set: function (value) {
  11434. if (this._applyFog === value) {
  11435. return;
  11436. }
  11437. this._applyFog = value;
  11438. this._markSubMeshesAsMiscDirty();
  11439. },
  11440. enumerable: true,
  11441. configurable: true
  11442. });
  11443. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11444. get: function () {
  11445. return this._collisionMask;
  11446. },
  11447. set: function (mask) {
  11448. this._collisionMask = !isNaN(mask) ? mask : -1;
  11449. },
  11450. enumerable: true,
  11451. configurable: true
  11452. });
  11453. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11454. get: function () {
  11455. return this._collisionGroup;
  11456. },
  11457. set: function (mask) {
  11458. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11459. },
  11460. enumerable: true,
  11461. configurable: true
  11462. });
  11463. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11464. get: function () {
  11465. return null;
  11466. },
  11467. enumerable: true,
  11468. configurable: true
  11469. });
  11470. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11471. get: function () {
  11472. return this._skeleton;
  11473. },
  11474. set: function (value) {
  11475. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11476. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11477. }
  11478. if (value && value.needInitialSkinMatrix) {
  11479. value._registerMeshWithPoseMatrix(this);
  11480. }
  11481. this._skeleton = value;
  11482. if (!this._skeleton) {
  11483. this._bonesTransformMatrices = null;
  11484. }
  11485. this._markSubMeshesAsAttributesDirty();
  11486. },
  11487. enumerable: true,
  11488. configurable: true
  11489. });
  11490. /**
  11491. * Returns the string "AbstractMesh"
  11492. */
  11493. AbstractMesh.prototype.getClassName = function () {
  11494. return "AbstractMesh";
  11495. };
  11496. /**
  11497. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11498. */
  11499. AbstractMesh.prototype.toString = function (fullDetails) {
  11500. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11501. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11502. if (this._skeleton) {
  11503. ret += ", skeleton: " + this._skeleton.name;
  11504. }
  11505. if (fullDetails) {
  11506. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11507. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11508. }
  11509. return ret;
  11510. };
  11511. AbstractMesh.prototype._resyncLightSources = function () {
  11512. this._lightSources.length = 0;
  11513. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11514. var light = _a[_i];
  11515. if (!light.isEnabled()) {
  11516. continue;
  11517. }
  11518. if (light.canAffectMesh(this)) {
  11519. this._lightSources.push(light);
  11520. }
  11521. }
  11522. this._markSubMeshesAsLightDirty();
  11523. };
  11524. AbstractMesh.prototype._resyncLighSource = function (light) {
  11525. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11526. var index = this._lightSources.indexOf(light);
  11527. if (index === -1) {
  11528. if (!isIn) {
  11529. return;
  11530. }
  11531. this._lightSources.push(light);
  11532. }
  11533. else {
  11534. if (isIn) {
  11535. return;
  11536. }
  11537. this._lightSources.splice(index, 1);
  11538. }
  11539. this._markSubMeshesAsLightDirty();
  11540. };
  11541. AbstractMesh.prototype._removeLightSource = function (light) {
  11542. var index = this._lightSources.indexOf(light);
  11543. if (index === -1) {
  11544. return;
  11545. }
  11546. this._lightSources.splice(index, 1);
  11547. };
  11548. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11549. if (!this.subMeshes) {
  11550. return;
  11551. }
  11552. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11553. var subMesh = _a[_i];
  11554. if (subMesh._materialDefines) {
  11555. func(subMesh._materialDefines);
  11556. }
  11557. }
  11558. };
  11559. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11560. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11561. };
  11562. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11563. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11564. };
  11565. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11566. if (!this.subMeshes) {
  11567. return;
  11568. }
  11569. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11570. var subMesh = _a[_i];
  11571. var material = subMesh.getMaterial();
  11572. if (material) {
  11573. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11574. }
  11575. }
  11576. };
  11577. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11578. /**
  11579. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11580. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11581. * Default : (0.0, 0.0, 0.0)
  11582. */
  11583. get: function () {
  11584. return this._rotation;
  11585. },
  11586. set: function (newRotation) {
  11587. this._rotation = newRotation;
  11588. },
  11589. enumerable: true,
  11590. configurable: true
  11591. });
  11592. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11593. /**
  11594. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11595. * Default : (1.0, 1.0, 1.0)
  11596. */
  11597. get: function () {
  11598. return this._scaling;
  11599. },
  11600. set: function (newScaling) {
  11601. this._scaling = newScaling;
  11602. if (this.physicsImpostor) {
  11603. this.physicsImpostor.forceUpdate();
  11604. }
  11605. },
  11606. enumerable: true,
  11607. configurable: true
  11608. });
  11609. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11610. /**
  11611. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11612. * It's null by default.
  11613. * 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)
  11614. */
  11615. get: function () {
  11616. return this._rotationQuaternion;
  11617. },
  11618. set: function (quaternion) {
  11619. this._rotationQuaternion = quaternion;
  11620. //reset the rotation vector.
  11621. if (quaternion && this.rotation.length()) {
  11622. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11623. }
  11624. },
  11625. enumerable: true,
  11626. configurable: true
  11627. });
  11628. // Methods
  11629. /**
  11630. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11631. * Returns the AbstractMesh.
  11632. */
  11633. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11634. this._poseMatrix.copyFrom(matrix);
  11635. return this;
  11636. };
  11637. /**
  11638. * Returns the mesh Pose matrix.
  11639. * Returned object : Matrix
  11640. */
  11641. AbstractMesh.prototype.getPoseMatrix = function () {
  11642. return this._poseMatrix;
  11643. };
  11644. /**
  11645. * Disables the mesh edger rendering mode.
  11646. * Returns the AbstractMesh.
  11647. */
  11648. AbstractMesh.prototype.disableEdgesRendering = function () {
  11649. if (this._edgesRenderer !== undefined) {
  11650. this._edgesRenderer.dispose();
  11651. this._edgesRenderer = undefined;
  11652. }
  11653. return this;
  11654. };
  11655. /**
  11656. * Enables the edge rendering mode on the mesh.
  11657. * This mode makes the mesh edges visible.
  11658. * Returns the AbstractMesh.
  11659. */
  11660. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11661. if (epsilon === void 0) { epsilon = 0.95; }
  11662. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11663. this.disableEdgesRendering();
  11664. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11665. return this;
  11666. };
  11667. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11668. /**
  11669. * Returns true if the mesh is blocked. Used by the class Mesh.
  11670. * Returns the boolean `false` by default.
  11671. */
  11672. get: function () {
  11673. return false;
  11674. },
  11675. enumerable: true,
  11676. configurable: true
  11677. });
  11678. /**
  11679. * Returns the mesh itself by default, used by the class Mesh.
  11680. * Returned type : AbstractMesh
  11681. */
  11682. AbstractMesh.prototype.getLOD = function (camera) {
  11683. return this;
  11684. };
  11685. /**
  11686. * Returns 0 by default, used by the class Mesh.
  11687. * Returns an integer.
  11688. */
  11689. AbstractMesh.prototype.getTotalVertices = function () {
  11690. return 0;
  11691. };
  11692. /**
  11693. * Returns null by default, used by the class Mesh.
  11694. * Returned type : integer array
  11695. */
  11696. AbstractMesh.prototype.getIndices = function () {
  11697. return null;
  11698. };
  11699. /**
  11700. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11701. * Returned type : float array or Float32Array
  11702. */
  11703. AbstractMesh.prototype.getVerticesData = function (kind) {
  11704. return null;
  11705. };
  11706. /**
  11707. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11708. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11709. * The `data` are either a numeric array either a Float32Array.
  11710. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11711. * 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).
  11712. * Note that a new underlying VertexBuffer object is created each call.
  11713. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11714. *
  11715. * Possible `kind` values :
  11716. * - BABYLON.VertexBuffer.PositionKind
  11717. * - BABYLON.VertexBuffer.UVKind
  11718. * - BABYLON.VertexBuffer.UV2Kind
  11719. * - BABYLON.VertexBuffer.UV3Kind
  11720. * - BABYLON.VertexBuffer.UV4Kind
  11721. * - BABYLON.VertexBuffer.UV5Kind
  11722. * - BABYLON.VertexBuffer.UV6Kind
  11723. * - BABYLON.VertexBuffer.ColorKind
  11724. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11725. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11726. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11727. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11728. *
  11729. * Returns the Mesh.
  11730. */
  11731. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11732. return null;
  11733. };
  11734. /**
  11735. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11736. * If the mesh has no geometry, it is simply returned as it is.
  11737. * The `data` are either a numeric array either a Float32Array.
  11738. * No new underlying VertexBuffer object is created.
  11739. * 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.
  11740. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11741. *
  11742. * Possible `kind` values :
  11743. * - BABYLON.VertexBuffer.PositionKind
  11744. * - BABYLON.VertexBuffer.UVKind
  11745. * - BABYLON.VertexBuffer.UV2Kind
  11746. * - BABYLON.VertexBuffer.UV3Kind
  11747. * - BABYLON.VertexBuffer.UV4Kind
  11748. * - BABYLON.VertexBuffer.UV5Kind
  11749. * - BABYLON.VertexBuffer.UV6Kind
  11750. * - BABYLON.VertexBuffer.ColorKind
  11751. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11752. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11753. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11754. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11755. *
  11756. * Returns the Mesh.
  11757. */
  11758. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11759. return null;
  11760. };
  11761. /**
  11762. * Sets the mesh indices.
  11763. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11764. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11765. * This method creates a new index buffer each call.
  11766. * Returns the Mesh.
  11767. */
  11768. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11769. return null;
  11770. };
  11771. /** Returns false by default, used by the class Mesh.
  11772. * Returns a boolean
  11773. */
  11774. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11775. return false;
  11776. };
  11777. /**
  11778. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11779. * Returns a BoundingInfo
  11780. */
  11781. AbstractMesh.prototype.getBoundingInfo = function () {
  11782. if (this._masterMesh) {
  11783. return this._masterMesh.getBoundingInfo();
  11784. }
  11785. if (!this._boundingInfo) {
  11786. this._updateBoundingInfo();
  11787. }
  11788. return this._boundingInfo;
  11789. };
  11790. /**
  11791. * Sets a mesh new object BoundingInfo.
  11792. * Returns the AbstractMesh.
  11793. */
  11794. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11795. this._boundingInfo = boundingInfo;
  11796. return this;
  11797. };
  11798. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11799. get: function () {
  11800. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. AbstractMesh.prototype._preActivate = function () {
  11806. };
  11807. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11808. };
  11809. AbstractMesh.prototype._activate = function (renderId) {
  11810. this._renderId = renderId;
  11811. };
  11812. /**
  11813. * Returns the last update of the World matrix
  11814. * Returns a Matrix.
  11815. */
  11816. AbstractMesh.prototype.getWorldMatrix = function () {
  11817. if (this._masterMesh) {
  11818. return this._masterMesh.getWorldMatrix();
  11819. }
  11820. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11821. this.computeWorldMatrix();
  11822. }
  11823. return this._worldMatrix;
  11824. };
  11825. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11826. /**
  11827. * Returns directly the last state of the mesh World matrix.
  11828. * A Matrix is returned.
  11829. */
  11830. get: function () {
  11831. return this._worldMatrix;
  11832. },
  11833. enumerable: true,
  11834. configurable: true
  11835. });
  11836. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11837. /**
  11838. * Returns the current mesh absolute position.
  11839. * Retuns a Vector3.
  11840. */
  11841. get: function () {
  11842. return this._absolutePosition;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. /**
  11848. * Prevents the World matrix to be computed any longer.
  11849. * Returns the AbstractMesh.
  11850. */
  11851. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11852. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11853. this.computeWorldMatrix(true);
  11854. this._isWorldMatrixFrozen = true;
  11855. return this;
  11856. };
  11857. /**
  11858. * Allows back the World matrix computation.
  11859. * Returns the AbstractMesh.
  11860. */
  11861. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11862. this._isWorldMatrixFrozen = false;
  11863. this.computeWorldMatrix(true);
  11864. return this;
  11865. };
  11866. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11867. /**
  11868. * True if the World matrix has been frozen.
  11869. * Returns a boolean.
  11870. */
  11871. get: function () {
  11872. return this._isWorldMatrixFrozen;
  11873. },
  11874. enumerable: true,
  11875. configurable: true
  11876. });
  11877. /**
  11878. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11879. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11880. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11881. * The passed axis is also normalized.
  11882. * Returns the AbstractMesh.
  11883. */
  11884. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11885. axis.normalize();
  11886. if (!this.rotationQuaternion) {
  11887. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11888. this.rotation = BABYLON.Vector3.Zero();
  11889. }
  11890. var rotationQuaternion;
  11891. if (!space || space === BABYLON.Space.LOCAL) {
  11892. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11893. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11894. }
  11895. else {
  11896. if (this.parent) {
  11897. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11898. invertParentWorldMatrix.invert();
  11899. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11900. }
  11901. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11902. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11903. }
  11904. return this;
  11905. };
  11906. /**
  11907. * Translates the mesh along the axis vector for the passed distance in the given space.
  11908. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11909. * Returns the AbstractMesh.
  11910. */
  11911. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11912. var displacementVector = axis.scale(distance);
  11913. if (!space || space === BABYLON.Space.LOCAL) {
  11914. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11915. this.setPositionWithLocalVector(tempV3);
  11916. }
  11917. else {
  11918. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11919. }
  11920. return this;
  11921. };
  11922. /**
  11923. * Adds a rotation step to the mesh current rotation.
  11924. * x, y, z are Euler angles expressed in radians.
  11925. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11926. * This means this rotation is made in the mesh local space only.
  11927. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11928. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11929. * ```javascript
  11930. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11931. * ```
  11932. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11933. * 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.
  11934. * Returns the AbstractMesh.
  11935. */
  11936. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11937. var rotationQuaternion;
  11938. if (this.rotationQuaternion) {
  11939. rotationQuaternion = this.rotationQuaternion;
  11940. }
  11941. else {
  11942. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11943. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11944. }
  11945. var accumulation = BABYLON.Tmp.Quaternion[0];
  11946. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11947. rotationQuaternion.multiplyInPlace(accumulation);
  11948. if (!this.rotationQuaternion) {
  11949. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11950. }
  11951. return this;
  11952. };
  11953. /**
  11954. * Retuns the mesh absolute position in the World.
  11955. * Returns a Vector3.
  11956. */
  11957. AbstractMesh.prototype.getAbsolutePosition = function () {
  11958. this.computeWorldMatrix();
  11959. return this._absolutePosition;
  11960. };
  11961. /**
  11962. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11963. * Returns the AbstractMesh.
  11964. */
  11965. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11966. if (!absolutePosition) {
  11967. return;
  11968. }
  11969. var absolutePositionX;
  11970. var absolutePositionY;
  11971. var absolutePositionZ;
  11972. if (absolutePosition.x === undefined) {
  11973. if (arguments.length < 3) {
  11974. return;
  11975. }
  11976. absolutePositionX = arguments[0];
  11977. absolutePositionY = arguments[1];
  11978. absolutePositionZ = arguments[2];
  11979. }
  11980. else {
  11981. absolutePositionX = absolutePosition.x;
  11982. absolutePositionY = absolutePosition.y;
  11983. absolutePositionZ = absolutePosition.z;
  11984. }
  11985. if (this.parent) {
  11986. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11987. invertParentWorldMatrix.invert();
  11988. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11989. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11990. }
  11991. else {
  11992. this.position.x = absolutePositionX;
  11993. this.position.y = absolutePositionY;
  11994. this.position.z = absolutePositionZ;
  11995. }
  11996. return this;
  11997. };
  11998. // ================================== Point of View Movement =================================
  11999. /**
  12000. * Perform relative position change from the point of view of behind the front of the mesh.
  12001. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12002. * Supports definition of mesh facing forward or backward.
  12003. * @param {number} amountRight
  12004. * @param {number} amountUp
  12005. * @param {number} amountForward
  12006. *
  12007. * Returns the AbstractMesh.
  12008. */
  12009. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12010. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12011. return this;
  12012. };
  12013. /**
  12014. * Calculate relative position change from the point of view of behind the front of the mesh.
  12015. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12016. * Supports definition of mesh facing forward or backward.
  12017. * @param {number} amountRight
  12018. * @param {number} amountUp
  12019. * @param {number} amountForward
  12020. *
  12021. * Returns a new Vector3.
  12022. */
  12023. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12024. var rotMatrix = new BABYLON.Matrix();
  12025. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12026. rotQuaternion.toRotationMatrix(rotMatrix);
  12027. var translationDelta = BABYLON.Vector3.Zero();
  12028. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12029. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12030. return translationDelta;
  12031. };
  12032. // ================================== Point of View Rotation =================================
  12033. /**
  12034. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12035. * Supports definition of mesh facing forward or backward.
  12036. * @param {number} flipBack
  12037. * @param {number} twirlClockwise
  12038. * @param {number} tiltRight
  12039. *
  12040. * Returns the AbstractMesh.
  12041. */
  12042. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12043. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12044. return this;
  12045. };
  12046. /**
  12047. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12048. * Supports definition of mesh facing forward or backward.
  12049. * @param {number} flipBack
  12050. * @param {number} twirlClockwise
  12051. * @param {number} tiltRight
  12052. *
  12053. * Returns a new Vector3.
  12054. */
  12055. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12056. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12057. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12058. };
  12059. /**
  12060. * Sets a new pivot matrix to the mesh.
  12061. * Returns the AbstractMesh.
  12062. */
  12063. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12064. this._pivotMatrix = matrix;
  12065. this._cache.pivotMatrixUpdated = true;
  12066. return this;
  12067. };
  12068. /**
  12069. * Returns the mesh pivot matrix.
  12070. * Default : Identity.
  12071. * A Matrix is returned.
  12072. */
  12073. AbstractMesh.prototype.getPivotMatrix = function () {
  12074. return this._pivotMatrix;
  12075. };
  12076. AbstractMesh.prototype._isSynchronized = function () {
  12077. if (this._isDirty) {
  12078. return false;
  12079. }
  12080. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12081. return false;
  12082. if (this._cache.pivotMatrixUpdated) {
  12083. return false;
  12084. }
  12085. if (this.infiniteDistance) {
  12086. return false;
  12087. }
  12088. if (!this._cache.position.equals(this.position))
  12089. return false;
  12090. if (this.rotationQuaternion) {
  12091. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12092. return false;
  12093. }
  12094. if (!this._cache.rotation.equals(this.rotation))
  12095. return false;
  12096. if (!this._cache.scaling.equals(this.scaling))
  12097. return false;
  12098. return true;
  12099. };
  12100. AbstractMesh.prototype._initCache = function () {
  12101. _super.prototype._initCache.call(this);
  12102. this._cache.localMatrixUpdated = false;
  12103. this._cache.position = BABYLON.Vector3.Zero();
  12104. this._cache.scaling = BABYLON.Vector3.Zero();
  12105. this._cache.rotation = BABYLON.Vector3.Zero();
  12106. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12107. this._cache.billboardMode = -1;
  12108. };
  12109. AbstractMesh.prototype.markAsDirty = function (property) {
  12110. if (property === "rotation") {
  12111. this.rotationQuaternion = null;
  12112. }
  12113. this._currentRenderId = Number.MAX_VALUE;
  12114. this._isDirty = true;
  12115. return this;
  12116. };
  12117. /**
  12118. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12119. * Returns the AbstractMesh.
  12120. */
  12121. AbstractMesh.prototype._updateBoundingInfo = function () {
  12122. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12123. this._boundingInfo.update(this.worldMatrixFromCache);
  12124. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12125. return this;
  12126. };
  12127. /**
  12128. * Update a mesh's children BoundingInfo objects only.
  12129. * Returns the AbstractMesh.
  12130. */
  12131. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12132. if (!this.subMeshes) {
  12133. return;
  12134. }
  12135. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12136. var subMesh = this.subMeshes[subIndex];
  12137. if (!subMesh.IsGlobal) {
  12138. subMesh.updateBoundingInfo(matrix);
  12139. }
  12140. }
  12141. return this;
  12142. };
  12143. /**
  12144. * Computes the mesh World matrix and returns it.
  12145. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12146. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12147. * If the parameter `force`is set to `true`, the actual computation is done.
  12148. * Returns the mesh World Matrix.
  12149. */
  12150. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12151. if (this._isWorldMatrixFrozen) {
  12152. return this._worldMatrix;
  12153. }
  12154. if (!force && this.isSynchronized(true)) {
  12155. this._currentRenderId = this.getScene().getRenderId();
  12156. return this._worldMatrix;
  12157. }
  12158. this._cache.position.copyFrom(this.position);
  12159. this._cache.scaling.copyFrom(this.scaling);
  12160. this._cache.pivotMatrixUpdated = false;
  12161. this._cache.billboardMode = this.billboardMode;
  12162. this._currentRenderId = this.getScene().getRenderId();
  12163. this._isDirty = false;
  12164. // Scaling
  12165. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12166. // Rotation
  12167. //rotate, if quaternion is set and rotation was used
  12168. if (this.rotationQuaternion) {
  12169. var len = this.rotation.length();
  12170. if (len) {
  12171. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12172. this.rotation.copyFromFloats(0, 0, 0);
  12173. }
  12174. }
  12175. if (this.rotationQuaternion) {
  12176. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12177. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12178. }
  12179. else {
  12180. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12181. this._cache.rotation.copyFrom(this.rotation);
  12182. }
  12183. // Translation
  12184. if (this.infiniteDistance && !this.parent) {
  12185. var camera = this.getScene().activeCamera;
  12186. if (camera) {
  12187. var cameraWorldMatrix = camera.getWorldMatrix();
  12188. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12189. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12190. }
  12191. }
  12192. else {
  12193. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12194. }
  12195. // Composing transformations
  12196. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12197. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12198. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12199. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12200. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12201. // Need to decompose each rotation here
  12202. var currentPosition = BABYLON.Tmp.Vector3[3];
  12203. if (this.parent && this.parent.getWorldMatrix) {
  12204. if (this._meshToBoneReferal) {
  12205. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12206. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12207. }
  12208. else {
  12209. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12210. }
  12211. }
  12212. else {
  12213. currentPosition.copyFrom(this.position);
  12214. }
  12215. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12216. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12217. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12218. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12219. }
  12220. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12221. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12222. }
  12223. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12224. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12225. }
  12226. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12227. }
  12228. else {
  12229. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12230. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12231. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12232. }
  12233. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12234. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12235. }
  12236. // Local world
  12237. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12238. // Parent
  12239. if (this.parent && this.parent.getWorldMatrix) {
  12240. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12241. if (this._meshToBoneReferal) {
  12242. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12243. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12244. }
  12245. else {
  12246. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12247. }
  12248. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12249. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12250. this._worldMatrix.copyFrom(this._localWorld);
  12251. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12252. }
  12253. else {
  12254. if (this._meshToBoneReferal) {
  12255. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12256. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12257. }
  12258. else {
  12259. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12260. }
  12261. }
  12262. this._markSyncedWithParent();
  12263. }
  12264. else {
  12265. this._worldMatrix.copyFrom(this._localWorld);
  12266. }
  12267. // Bounding info
  12268. this._updateBoundingInfo();
  12269. // Absolute position
  12270. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12271. // Callbacks
  12272. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12273. if (!this._poseMatrix) {
  12274. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12275. }
  12276. return this._worldMatrix;
  12277. };
  12278. /**
  12279. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12280. * @param func: callback function to add
  12281. *
  12282. * Returns the AbstractMesh.
  12283. */
  12284. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12285. this.onAfterWorldMatrixUpdateObservable.add(func);
  12286. return this;
  12287. };
  12288. /**
  12289. * Removes a registered callback function.
  12290. * Returns the AbstractMesh.
  12291. */
  12292. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12293. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12294. return this;
  12295. };
  12296. /**
  12297. * Sets the mesh position in its local space.
  12298. * Returns the AbstractMesh.
  12299. */
  12300. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12301. this.computeWorldMatrix();
  12302. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12303. return this;
  12304. };
  12305. /**
  12306. * Returns the mesh position in the local space from the current World matrix values.
  12307. * Returns a new Vector3.
  12308. */
  12309. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12310. this.computeWorldMatrix();
  12311. var invLocalWorldMatrix = this._localWorld.clone();
  12312. invLocalWorldMatrix.invert();
  12313. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12314. };
  12315. /**
  12316. * Translates the mesh along the passed Vector3 in its local space.
  12317. * Returns the AbstractMesh.
  12318. */
  12319. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12320. this.computeWorldMatrix(true);
  12321. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12322. return this;
  12323. };
  12324. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12325. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12326. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12327. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12328. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12329. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12330. /// <returns>Mesh oriented towards targetMesh</returns>
  12331. if (yawCor === void 0) { yawCor = 0; }
  12332. if (pitchCor === void 0) { pitchCor = 0; }
  12333. if (rollCor === void 0) { rollCor = 0; }
  12334. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12335. var dv = AbstractMesh._lookAtVectorCache;
  12336. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12337. targetPoint.subtractToRef(pos, dv);
  12338. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12339. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12340. var pitch = Math.atan2(dv.y, len);
  12341. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12342. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12343. return this;
  12344. };
  12345. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12346. this._meshToBoneReferal = affectedMesh;
  12347. this.parent = bone;
  12348. if (bone.getWorldMatrix().determinant() < 0) {
  12349. this.scalingDeterminant *= -1;
  12350. }
  12351. return this;
  12352. };
  12353. AbstractMesh.prototype.detachFromBone = function () {
  12354. if (this.parent.getWorldMatrix().determinant() < 0) {
  12355. this.scalingDeterminant *= -1;
  12356. }
  12357. this._meshToBoneReferal = null;
  12358. this.parent = null;
  12359. return this;
  12360. };
  12361. /**
  12362. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12363. * A mesh is in the frustum if its bounding box intersects the frustum.
  12364. * Boolean returned.
  12365. */
  12366. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12367. return this._boundingInfo.isInFrustum(frustumPlanes);
  12368. };
  12369. /**
  12370. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12371. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12372. * Boolean returned.
  12373. */
  12374. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12375. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12376. ;
  12377. };
  12378. /**
  12379. * True if the mesh intersects another mesh or a SolidParticle object.
  12380. * 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)
  12381. * Returns a boolean.
  12382. */
  12383. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12384. if (!this._boundingInfo || !mesh._boundingInfo) {
  12385. return false;
  12386. }
  12387. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12388. };
  12389. /**
  12390. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12391. * Returns a boolean.
  12392. */
  12393. AbstractMesh.prototype.intersectsPoint = function (point) {
  12394. if (!this._boundingInfo) {
  12395. return false;
  12396. }
  12397. return this._boundingInfo.intersectsPoint(point);
  12398. };
  12399. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12400. return this.physicsImpostor;
  12401. };
  12402. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12403. if (!camera) {
  12404. camera = this.getScene().activeCamera;
  12405. }
  12406. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12407. };
  12408. /**
  12409. * Returns the distance from the mesh to the active camera.
  12410. * Returns a float.
  12411. */
  12412. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12413. if (!camera) {
  12414. camera = this.getScene().activeCamera;
  12415. }
  12416. return this.absolutePosition.subtract(camera.position).length();
  12417. };
  12418. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12419. if (!this.physicsImpostor) {
  12420. return;
  12421. }
  12422. this.physicsImpostor.applyImpulse(force, contactPoint);
  12423. return this;
  12424. };
  12425. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12426. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12427. return;
  12428. }
  12429. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12430. mainPivot: pivot1,
  12431. connectedPivot: pivot2,
  12432. nativeParams: options
  12433. });
  12434. return this;
  12435. };
  12436. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12437. // Collisions
  12438. /**
  12439. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12440. * Default `false`.
  12441. */
  12442. get: function () {
  12443. return this._checkCollisions;
  12444. },
  12445. set: function (collisionEnabled) {
  12446. this._checkCollisions = collisionEnabled;
  12447. if (this.getScene().workerCollisions) {
  12448. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12449. }
  12450. },
  12451. enumerable: true,
  12452. configurable: true
  12453. });
  12454. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12455. var globalPosition = this.getAbsolutePosition();
  12456. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12457. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12458. if (!this._collider) {
  12459. this._collider = new BABYLON.Collider();
  12460. }
  12461. this._collider.radius = this.ellipsoid;
  12462. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12463. return this;
  12464. };
  12465. // Submeshes octree
  12466. /**
  12467. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12468. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12469. * Returns an Octree of submeshes.
  12470. */
  12471. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12472. if (maxCapacity === void 0) { maxCapacity = 64; }
  12473. if (maxDepth === void 0) { maxDepth = 2; }
  12474. if (!this._submeshesOctree) {
  12475. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12476. }
  12477. this.computeWorldMatrix(true);
  12478. // Update octree
  12479. var bbox = this.getBoundingInfo().boundingBox;
  12480. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12481. return this._submeshesOctree;
  12482. };
  12483. // Collisions
  12484. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12485. this._generatePointsArray();
  12486. // Transformation
  12487. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12488. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12489. subMesh._lastColliderWorldVertices = [];
  12490. subMesh._trianglePlanes = [];
  12491. var start = subMesh.verticesStart;
  12492. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12493. for (var i = start; i < end; i++) {
  12494. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12495. }
  12496. }
  12497. // Collide
  12498. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12499. if (collider.collisionFound) {
  12500. collider.collidedMesh = this;
  12501. }
  12502. return this;
  12503. };
  12504. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12505. var subMeshes;
  12506. var len;
  12507. // Octrees
  12508. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12509. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12510. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12511. len = intersections.length;
  12512. subMeshes = intersections.data;
  12513. }
  12514. else {
  12515. subMeshes = this.subMeshes;
  12516. len = subMeshes.length;
  12517. }
  12518. for (var index = 0; index < len; index++) {
  12519. var subMesh = subMeshes[index];
  12520. // Bounding test
  12521. if (len > 1 && !subMesh._checkCollision(collider))
  12522. continue;
  12523. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12524. }
  12525. return this;
  12526. };
  12527. AbstractMesh.prototype._checkCollision = function (collider) {
  12528. // Bounding box test
  12529. if (!this._boundingInfo._checkCollision(collider))
  12530. return this;
  12531. // Transformation matrix
  12532. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12533. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12534. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12535. return this;
  12536. };
  12537. // Picking
  12538. AbstractMesh.prototype._generatePointsArray = function () {
  12539. return false;
  12540. };
  12541. /**
  12542. * Checks if the passed Ray intersects with the mesh.
  12543. * Returns an object PickingInfo.
  12544. */
  12545. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12546. var pickingInfo = new BABYLON.PickingInfo();
  12547. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12548. return pickingInfo;
  12549. }
  12550. if (!this._generatePointsArray()) {
  12551. return pickingInfo;
  12552. }
  12553. var intersectInfo = null;
  12554. // Octrees
  12555. var subMeshes;
  12556. var len;
  12557. if (this._submeshesOctree && this.useOctreeForPicking) {
  12558. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12559. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12560. len = intersections.length;
  12561. subMeshes = intersections.data;
  12562. }
  12563. else {
  12564. subMeshes = this.subMeshes;
  12565. len = subMeshes.length;
  12566. }
  12567. for (var index = 0; index < len; index++) {
  12568. var subMesh = subMeshes[index];
  12569. // Bounding test
  12570. if (len > 1 && !subMesh.canIntersects(ray))
  12571. continue;
  12572. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12573. if (currentIntersectInfo) {
  12574. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12575. intersectInfo = currentIntersectInfo;
  12576. intersectInfo.subMeshId = index;
  12577. if (fastCheck) {
  12578. break;
  12579. }
  12580. }
  12581. }
  12582. }
  12583. if (intersectInfo) {
  12584. // Get picked point
  12585. var world = this.getWorldMatrix();
  12586. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12587. var direction = ray.direction.clone();
  12588. direction = direction.scale(intersectInfo.distance);
  12589. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12590. var pickedPoint = worldOrigin.add(worldDirection);
  12591. // Return result
  12592. pickingInfo.hit = true;
  12593. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12594. pickingInfo.pickedPoint = pickedPoint;
  12595. pickingInfo.pickedMesh = this;
  12596. pickingInfo.bu = intersectInfo.bu;
  12597. pickingInfo.bv = intersectInfo.bv;
  12598. pickingInfo.faceId = intersectInfo.faceId;
  12599. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12600. return pickingInfo;
  12601. }
  12602. return pickingInfo;
  12603. };
  12604. /**
  12605. * Clones the mesh, used by the class Mesh.
  12606. * Just returns `null` for an AbstractMesh.
  12607. */
  12608. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12609. return null;
  12610. };
  12611. /**
  12612. * Disposes all the mesh submeshes.
  12613. * Returns the AbstractMesh.
  12614. */
  12615. AbstractMesh.prototype.releaseSubMeshes = function () {
  12616. if (this.subMeshes) {
  12617. while (this.subMeshes.length) {
  12618. this.subMeshes[0].dispose();
  12619. }
  12620. }
  12621. else {
  12622. this.subMeshes = new Array();
  12623. }
  12624. return this;
  12625. };
  12626. /**
  12627. * Disposes the AbstractMesh.
  12628. * Some internal references are kept for further use.
  12629. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12630. * Returns nothing.
  12631. */
  12632. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12633. var _this = this;
  12634. var index;
  12635. // Action manager
  12636. if (this.actionManager) {
  12637. this.actionManager.dispose();
  12638. this.actionManager = null;
  12639. }
  12640. // Skeleton
  12641. this.skeleton = null;
  12642. // Animations
  12643. this.getScene().stopAnimation(this);
  12644. // Physics
  12645. if (this.physicsImpostor) {
  12646. this.physicsImpostor.dispose();
  12647. }
  12648. // Intersections in progress
  12649. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12650. var other = this._intersectionsInProgress[index];
  12651. var pos = other._intersectionsInProgress.indexOf(this);
  12652. other._intersectionsInProgress.splice(pos, 1);
  12653. }
  12654. this._intersectionsInProgress = [];
  12655. // Lights
  12656. var lights = this.getScene().lights;
  12657. lights.forEach(function (light) {
  12658. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12659. if (meshIndex !== -1) {
  12660. light.includedOnlyMeshes.splice(meshIndex, 1);
  12661. }
  12662. meshIndex = light.excludedMeshes.indexOf(_this);
  12663. if (meshIndex !== -1) {
  12664. light.excludedMeshes.splice(meshIndex, 1);
  12665. }
  12666. // Shadow generators
  12667. var generator = light.getShadowGenerator();
  12668. if (generator) {
  12669. var shadowMap = generator.getShadowMap();
  12670. meshIndex = shadowMap.renderList.indexOf(_this);
  12671. if (meshIndex !== -1) {
  12672. shadowMap.renderList.splice(meshIndex, 1);
  12673. }
  12674. }
  12675. });
  12676. // Edges
  12677. if (this._edgesRenderer) {
  12678. this._edgesRenderer.dispose();
  12679. this._edgesRenderer = null;
  12680. }
  12681. // SubMeshes
  12682. if (this.getClassName() !== "InstancedMesh") {
  12683. this.releaseSubMeshes();
  12684. }
  12685. // Octree
  12686. var sceneOctree = this.getScene().selectionOctree;
  12687. if (sceneOctree) {
  12688. var index = sceneOctree.dynamicContent.indexOf(this);
  12689. if (index !== -1) {
  12690. sceneOctree.dynamicContent.splice(index, 1);
  12691. }
  12692. }
  12693. // Engine
  12694. this.getScene().getEngine().wipeCaches();
  12695. // Remove from scene
  12696. this.getScene().removeMesh(this);
  12697. if (!doNotRecurse) {
  12698. // Particles
  12699. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12700. if (this.getScene().particleSystems[index].emitter === this) {
  12701. this.getScene().particleSystems[index].dispose();
  12702. index--;
  12703. }
  12704. }
  12705. // Children
  12706. var objects = this.getDescendants(true);
  12707. for (index = 0; index < objects.length; index++) {
  12708. objects[index].dispose();
  12709. }
  12710. }
  12711. else {
  12712. var childMeshes = this.getChildMeshes(true);
  12713. for (index = 0; index < childMeshes.length; index++) {
  12714. var child = childMeshes[index];
  12715. child.parent = null;
  12716. child.computeWorldMatrix(true);
  12717. }
  12718. }
  12719. // facet data
  12720. if (this._facetDataEnabled) {
  12721. this.disableFacetData();
  12722. }
  12723. this.onAfterWorldMatrixUpdateObservable.clear();
  12724. this.onCollideObservable.clear();
  12725. this.onCollisionPositionChangeObservable.clear();
  12726. this._isDisposed = true;
  12727. _super.prototype.dispose.call(this);
  12728. };
  12729. /**
  12730. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12731. * This Vector3 is expressed in the World space.
  12732. */
  12733. AbstractMesh.prototype.getDirection = function (localAxis) {
  12734. var result = BABYLON.Vector3.Zero();
  12735. this.getDirectionToRef(localAxis, result);
  12736. return result;
  12737. };
  12738. /**
  12739. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12740. * localAxis is expressed in the mesh local space.
  12741. * result is computed in the Wordl space from the mesh World matrix.
  12742. * Returns the AbstractMesh.
  12743. */
  12744. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12745. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12746. return this;
  12747. };
  12748. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12749. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12750. if (this.getScene().getRenderId() == 0) {
  12751. this.computeWorldMatrix(true);
  12752. }
  12753. var wm = this.getWorldMatrix();
  12754. if (space == BABYLON.Space.WORLD) {
  12755. var tmat = BABYLON.Tmp.Matrix[0];
  12756. wm.invertToRef(tmat);
  12757. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12758. }
  12759. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12760. this._pivotMatrix.m[12] = -point.x;
  12761. this._pivotMatrix.m[13] = -point.y;
  12762. this._pivotMatrix.m[14] = -point.z;
  12763. this._cache.pivotMatrixUpdated = true;
  12764. return this;
  12765. };
  12766. /**
  12767. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12768. */
  12769. AbstractMesh.prototype.getPivotPoint = function () {
  12770. var point = BABYLON.Vector3.Zero();
  12771. this.getPivotPointToRef(point);
  12772. return point;
  12773. };
  12774. /**
  12775. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12776. * Returns the AbstractMesh.
  12777. */
  12778. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12779. result.x = -this._pivotMatrix.m[12];
  12780. result.y = -this._pivotMatrix.m[13];
  12781. result.z = -this._pivotMatrix.m[14];
  12782. return this;
  12783. };
  12784. /**
  12785. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12786. */
  12787. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12788. var point = BABYLON.Vector3.Zero();
  12789. this.getAbsolutePivotPointToRef(point);
  12790. return point;
  12791. };
  12792. /**
  12793. * Defines the passed mesh as the parent of the current mesh.
  12794. * Returns the AbstractMesh.
  12795. */
  12796. AbstractMesh.prototype.setParent = function (mesh) {
  12797. var child = this;
  12798. var parent = mesh;
  12799. if (mesh == null) {
  12800. var rotation = BABYLON.Tmp.Quaternion[0];
  12801. var position = BABYLON.Tmp.Vector3[0];
  12802. var scale = BABYLON.Tmp.Vector3[1];
  12803. child.getWorldMatrix().decompose(scale, rotation, position);
  12804. if (child.rotationQuaternion) {
  12805. child.rotationQuaternion.copyFrom(rotation);
  12806. }
  12807. else {
  12808. rotation.toEulerAnglesToRef(child.rotation);
  12809. }
  12810. child.position.x = position.x;
  12811. child.position.y = position.y;
  12812. child.position.z = position.z;
  12813. }
  12814. else {
  12815. var rotation = BABYLON.Tmp.Quaternion[0];
  12816. var position = BABYLON.Tmp.Vector3[0];
  12817. var scale = BABYLON.Tmp.Vector3[1];
  12818. var m1 = BABYLON.Tmp.Matrix[0];
  12819. var m2 = BABYLON.Tmp.Matrix[1];
  12820. parent.getWorldMatrix().decompose(scale, rotation, position);
  12821. rotation.toRotationMatrix(m1);
  12822. m2.setTranslation(position);
  12823. m2.multiplyToRef(m1, m1);
  12824. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12825. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12826. m.decompose(scale, rotation, position);
  12827. if (child.rotationQuaternion) {
  12828. child.rotationQuaternion.copyFrom(rotation);
  12829. }
  12830. else {
  12831. rotation.toEulerAnglesToRef(child.rotation);
  12832. }
  12833. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12834. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12835. m.decompose(scale, rotation, position);
  12836. child.position.x = position.x;
  12837. child.position.y = position.y;
  12838. child.position.z = position.z;
  12839. }
  12840. child.parent = parent;
  12841. return this;
  12842. };
  12843. /**
  12844. * Adds the passed mesh as a child to the current mesh.
  12845. * Returns the AbstractMesh.
  12846. */
  12847. AbstractMesh.prototype.addChild = function (mesh) {
  12848. mesh.setParent(this);
  12849. return this;
  12850. };
  12851. /**
  12852. * Removes the passed mesh from the current mesh children list.
  12853. * Returns the AbstractMesh.
  12854. */
  12855. AbstractMesh.prototype.removeChild = function (mesh) {
  12856. mesh.setParent(null);
  12857. return this;
  12858. };
  12859. /**
  12860. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12861. * Returns the AbstractMesh.
  12862. */
  12863. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12864. result.x = this._pivotMatrix.m[12];
  12865. result.y = this._pivotMatrix.m[13];
  12866. result.z = this._pivotMatrix.m[14];
  12867. this.getPivotPointToRef(result);
  12868. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12869. return this;
  12870. };
  12871. // Facet data
  12872. /**
  12873. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12874. * Returns the AbstractMesh.
  12875. */
  12876. AbstractMesh.prototype._initFacetData = function () {
  12877. if (!this._facetNormals) {
  12878. this._facetNormals = new Array();
  12879. }
  12880. if (!this._facetPositions) {
  12881. this._facetPositions = new Array();
  12882. }
  12883. if (!this._facetPartitioning) {
  12884. this._facetPartitioning = new Array();
  12885. }
  12886. this._facetNb = this.getIndices().length / 3;
  12887. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12888. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12889. for (var f = 0; f < this._facetNb; f++) {
  12890. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12891. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12892. }
  12893. this._facetDataEnabled = true;
  12894. return this;
  12895. };
  12896. /**
  12897. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12898. * This method can be called within the render loop.
  12899. * 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.
  12900. * Returns the AbstractMesh.
  12901. */
  12902. AbstractMesh.prototype.updateFacetData = function () {
  12903. if (!this._facetDataEnabled) {
  12904. this._initFacetData();
  12905. }
  12906. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12907. var indices = this.getIndices();
  12908. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12909. var bInfo = this.getBoundingInfo();
  12910. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12911. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12912. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12913. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12914. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12915. this._subDiv.max = this._partitioningSubdivisions;
  12916. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12917. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12918. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12919. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12920. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12921. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12922. // set the parameters for ComputeNormals()
  12923. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12924. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12925. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12926. this._facetParameters.bInfo = bInfo;
  12927. this._facetParameters.bbSize = this._bbSize;
  12928. this._facetParameters.subDiv = this._subDiv;
  12929. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12930. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12931. return this;
  12932. };
  12933. /**
  12934. * Returns the facetLocalNormals array.
  12935. * The normals are expressed in the mesh local space.
  12936. */
  12937. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12938. if (!this._facetNormals) {
  12939. this.updateFacetData();
  12940. }
  12941. return this._facetNormals;
  12942. };
  12943. /**
  12944. * Returns the facetLocalPositions array.
  12945. * The facet positions are expressed in the mesh local space.
  12946. */
  12947. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12948. if (!this._facetPositions) {
  12949. this.updateFacetData();
  12950. }
  12951. return this._facetPositions;
  12952. };
  12953. /**
  12954. * Returns the facetLocalPartioning array.
  12955. */
  12956. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12957. if (!this._facetPartitioning) {
  12958. this.updateFacetData();
  12959. }
  12960. return this._facetPartitioning;
  12961. };
  12962. /**
  12963. * Returns the i-th facet position in the world system.
  12964. * This method allocates a new Vector3 per call.
  12965. */
  12966. AbstractMesh.prototype.getFacetPosition = function (i) {
  12967. var pos = BABYLON.Vector3.Zero();
  12968. this.getFacetPositionToRef(i, pos);
  12969. return pos;
  12970. };
  12971. /**
  12972. * Sets the reference Vector3 with the i-th facet position in the world system.
  12973. * Returns the AbstractMesh.
  12974. */
  12975. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12976. var localPos = (this.getFacetLocalPositions())[i];
  12977. var world = this.getWorldMatrix();
  12978. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12979. return this;
  12980. };
  12981. /**
  12982. * Returns the i-th facet normal in the world system.
  12983. * This method allocates a new Vector3 per call.
  12984. */
  12985. AbstractMesh.prototype.getFacetNormal = function (i) {
  12986. var norm = BABYLON.Vector3.Zero();
  12987. this.getFacetNormalToRef(i, norm);
  12988. return norm;
  12989. };
  12990. /**
  12991. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12992. * Returns the AbstractMesh.
  12993. */
  12994. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12995. var localNorm = (this.getFacetLocalNormals())[i];
  12996. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12997. return this;
  12998. };
  12999. /**
  13000. * 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).
  13001. */
  13002. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13003. var bInfo = this.getBoundingInfo();
  13004. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13005. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13006. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13007. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13008. return null;
  13009. }
  13010. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13011. };
  13012. /**
  13013. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13014. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13015. * 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.
  13016. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13017. * 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.
  13018. */
  13019. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13020. if (checkFace === void 0) { checkFace = false; }
  13021. if (facing === void 0) { facing = true; }
  13022. var world = this.getWorldMatrix();
  13023. var invMat = BABYLON.Tmp.Matrix[5];
  13024. world.invertToRef(invMat);
  13025. var invVect = BABYLON.Tmp.Vector3[8];
  13026. var closest = null;
  13027. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13028. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13029. if (projected) {
  13030. // tranform the local computed projected vector to world coordinates
  13031. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13032. }
  13033. return closest;
  13034. };
  13035. /**
  13036. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13037. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13038. * 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.
  13039. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13040. * 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.
  13041. */
  13042. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13043. if (checkFace === void 0) { checkFace = false; }
  13044. if (facing === void 0) { facing = true; }
  13045. var closest = null;
  13046. var tmpx = 0.0;
  13047. var tmpy = 0.0;
  13048. var tmpz = 0.0;
  13049. var d = 0.0; // tmp dot facet normal * facet position
  13050. var t0 = 0.0;
  13051. var projx = 0.0;
  13052. var projy = 0.0;
  13053. var projz = 0.0;
  13054. // Get all the facets in the same partitioning block than (x, y, z)
  13055. var facetPositions = this.getFacetLocalPositions();
  13056. var facetNormals = this.getFacetLocalNormals();
  13057. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13058. if (!facetsInBlock) {
  13059. return null;
  13060. }
  13061. // Get the closest facet to (x, y, z)
  13062. var shortest = Number.MAX_VALUE; // init distance vars
  13063. var tmpDistance = shortest;
  13064. var fib; // current facet in the block
  13065. var norm; // current facet normal
  13066. var p0; // current facet barycenter position
  13067. // loop on all the facets in the current partitioning block
  13068. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13069. fib = facetsInBlock[idx];
  13070. norm = facetNormals[fib];
  13071. p0 = facetPositions[fib];
  13072. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13073. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13074. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13075. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13076. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13077. projx = x + norm.x * t0;
  13078. projy = y + norm.y * t0;
  13079. projz = z + norm.z * t0;
  13080. tmpx = projx - x;
  13081. tmpy = projy - y;
  13082. tmpz = projz - z;
  13083. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13084. if (tmpDistance < shortest) {
  13085. shortest = tmpDistance;
  13086. closest = fib;
  13087. if (projected) {
  13088. projected.x = projx;
  13089. projected.y = projy;
  13090. projected.z = projz;
  13091. }
  13092. }
  13093. }
  13094. }
  13095. return closest;
  13096. };
  13097. /**
  13098. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13099. */
  13100. AbstractMesh.prototype.getFacetDataParameters = function () {
  13101. return this._facetParameters;
  13102. };
  13103. /**
  13104. * Disables the feature FacetData and frees the related memory.
  13105. * Returns the AbstractMesh.
  13106. */
  13107. AbstractMesh.prototype.disableFacetData = function () {
  13108. if (this._facetDataEnabled) {
  13109. this._facetDataEnabled = false;
  13110. this._facetPositions = null;
  13111. this._facetNormals = null;
  13112. this._facetPartitioning = null;
  13113. this._facetParameters = null;
  13114. }
  13115. return this;
  13116. };
  13117. /**
  13118. * Creates new normals data for the mesh.
  13119. * @param updatable.
  13120. */
  13121. AbstractMesh.prototype.createNormals = function (updatable) {
  13122. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13123. var indices = this.getIndices();
  13124. var normals;
  13125. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13126. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13127. }
  13128. else {
  13129. normals = [];
  13130. }
  13131. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13132. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13133. };
  13134. return AbstractMesh;
  13135. }(BABYLON.Node));
  13136. // Statics
  13137. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13138. AbstractMesh._BILLBOARDMODE_X = 1;
  13139. AbstractMesh._BILLBOARDMODE_Y = 2;
  13140. AbstractMesh._BILLBOARDMODE_Z = 4;
  13141. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13142. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13143. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13144. BABYLON.AbstractMesh = AbstractMesh;
  13145. })(BABYLON || (BABYLON = {}));
  13146. //# sourceMappingURL=babylon.abstractMesh.js.map
  13147. var BABYLON;
  13148. (function (BABYLON) {
  13149. var Light = (function (_super) {
  13150. __extends(Light, _super);
  13151. /**
  13152. * Creates a Light object in the scene.
  13153. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13154. */
  13155. function Light(name, scene) {
  13156. var _this = _super.call(this, name, scene) || this;
  13157. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13158. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13159. _this.intensity = 1.0;
  13160. _this.range = Number.MAX_VALUE;
  13161. /**
  13162. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13163. * of light.
  13164. */
  13165. _this._photometricScale = 1.0;
  13166. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13167. _this._radius = 0.00001;
  13168. _this.renderPriority = 0;
  13169. /**
  13170. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13171. * the current shadow generator.
  13172. */
  13173. _this.shadowEnabled = true;
  13174. _this._excludeWithLayerMask = 0;
  13175. _this._includeOnlyWithLayerMask = 0;
  13176. _this._lightmapMode = 0;
  13177. _this._excludedMeshesIds = new Array();
  13178. _this._includedOnlyMeshesIds = new Array();
  13179. _this.getScene().addLight(_this);
  13180. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13181. _this._buildUniformLayout();
  13182. _this.includedOnlyMeshes = new Array();
  13183. _this.excludedMeshes = new Array();
  13184. _this._resyncMeshes();
  13185. return _this;
  13186. }
  13187. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13188. /**
  13189. * If every light affecting the material is in this lightmapMode,
  13190. * material.lightmapTexture adds or multiplies
  13191. * (depends on material.useLightmapAsShadowmap)
  13192. * after every other light calculations.
  13193. */
  13194. get: function () {
  13195. return Light._LIGHTMAP_DEFAULT;
  13196. },
  13197. enumerable: true,
  13198. configurable: true
  13199. });
  13200. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13201. /**
  13202. * material.lightmapTexture as only diffuse lighting from this light
  13203. * adds pnly specular lighting from this light
  13204. * adds dynamic shadows
  13205. */
  13206. get: function () {
  13207. return Light._LIGHTMAP_SPECULAR;
  13208. },
  13209. enumerable: true,
  13210. configurable: true
  13211. });
  13212. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13213. /**
  13214. * material.lightmapTexture as only lighting
  13215. * no light calculation from this light
  13216. * only adds dynamic shadows from this light
  13217. */
  13218. get: function () {
  13219. return Light._LIGHTMAP_SHADOWSONLY;
  13220. },
  13221. enumerable: true,
  13222. configurable: true
  13223. });
  13224. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13225. /**
  13226. * Each light type uses the default quantity according to its type:
  13227. * point/spot lights use luminous intensity
  13228. * directional lights use illuminance
  13229. */
  13230. get: function () {
  13231. return Light._INTENSITYMODE_AUTOMATIC;
  13232. },
  13233. enumerable: true,
  13234. configurable: true
  13235. });
  13236. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13237. /**
  13238. * lumen (lm)
  13239. */
  13240. get: function () {
  13241. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13242. },
  13243. enumerable: true,
  13244. configurable: true
  13245. });
  13246. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13247. /**
  13248. * candela (lm/sr)
  13249. */
  13250. get: function () {
  13251. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13252. },
  13253. enumerable: true,
  13254. configurable: true
  13255. });
  13256. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13257. /**
  13258. * lux (lm/m^2)
  13259. */
  13260. get: function () {
  13261. return Light._INTENSITYMODE_ILLUMINANCE;
  13262. },
  13263. enumerable: true,
  13264. configurable: true
  13265. });
  13266. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13267. /**
  13268. * nit (cd/m^2)
  13269. */
  13270. get: function () {
  13271. return Light._INTENSITYMODE_LUMINANCE;
  13272. },
  13273. enumerable: true,
  13274. configurable: true
  13275. });
  13276. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13277. /**
  13278. * Light type const id of the point light.
  13279. */
  13280. get: function () {
  13281. return Light._LIGHTTYPEID_POINTLIGHT;
  13282. },
  13283. enumerable: true,
  13284. configurable: true
  13285. });
  13286. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13287. /**
  13288. * Light type const id of the directional light.
  13289. */
  13290. get: function () {
  13291. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13292. },
  13293. enumerable: true,
  13294. configurable: true
  13295. });
  13296. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13297. /**
  13298. * Light type const id of the spot light.
  13299. */
  13300. get: function () {
  13301. return Light._LIGHTTYPEID_SPOTLIGHT;
  13302. },
  13303. enumerable: true,
  13304. configurable: true
  13305. });
  13306. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13307. /**
  13308. * Light type const id of the hemispheric light.
  13309. */
  13310. get: function () {
  13311. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13312. },
  13313. enumerable: true,
  13314. configurable: true
  13315. });
  13316. Object.defineProperty(Light.prototype, "intensityMode", {
  13317. /**
  13318. * Gets the photometric scale used to interpret the intensity.
  13319. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13320. */
  13321. get: function () {
  13322. return this._intensityMode;
  13323. },
  13324. /**
  13325. * Sets the photometric scale used to interpret the intensity.
  13326. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13327. */
  13328. set: function (value) {
  13329. this._intensityMode = value;
  13330. this._computePhotometricScale();
  13331. },
  13332. enumerable: true,
  13333. configurable: true
  13334. });
  13335. ;
  13336. ;
  13337. Object.defineProperty(Light.prototype, "radius", {
  13338. /**
  13339. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13340. */
  13341. get: function () {
  13342. return this._radius;
  13343. },
  13344. /**
  13345. * sets the light radius used by PBR Materials to simulate soft area lights.
  13346. */
  13347. set: function (value) {
  13348. this._radius = value;
  13349. this._computePhotometricScale();
  13350. },
  13351. enumerable: true,
  13352. configurable: true
  13353. });
  13354. ;
  13355. ;
  13356. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13357. get: function () {
  13358. return this._includedOnlyMeshes;
  13359. },
  13360. set: function (value) {
  13361. this._includedOnlyMeshes = value;
  13362. this._hookArrayForIncludedOnly(value);
  13363. },
  13364. enumerable: true,
  13365. configurable: true
  13366. });
  13367. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13368. get: function () {
  13369. return this._excludedMeshes;
  13370. },
  13371. set: function (value) {
  13372. this._excludedMeshes = value;
  13373. this._hookArrayForExcluded(value);
  13374. },
  13375. enumerable: true,
  13376. configurable: true
  13377. });
  13378. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13379. get: function () {
  13380. return this._excludeWithLayerMask;
  13381. },
  13382. set: function (value) {
  13383. this._excludeWithLayerMask = value;
  13384. this._resyncMeshes();
  13385. },
  13386. enumerable: true,
  13387. configurable: true
  13388. });
  13389. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13390. get: function () {
  13391. return this._includeOnlyWithLayerMask;
  13392. },
  13393. set: function (value) {
  13394. this._includeOnlyWithLayerMask = value;
  13395. this._resyncMeshes();
  13396. },
  13397. enumerable: true,
  13398. configurable: true
  13399. });
  13400. Object.defineProperty(Light.prototype, "lightmapMode", {
  13401. get: function () {
  13402. return this._lightmapMode;
  13403. },
  13404. set: function (value) {
  13405. if (this._lightmapMode === value) {
  13406. return;
  13407. }
  13408. this._lightmapMode = value;
  13409. this._markMeshesAsLightDirty();
  13410. },
  13411. enumerable: true,
  13412. configurable: true
  13413. });
  13414. Light.prototype._buildUniformLayout = function () {
  13415. // Overridden
  13416. };
  13417. /**
  13418. * Returns the string "Light".
  13419. */
  13420. Light.prototype.getClassName = function () {
  13421. return "Light";
  13422. };
  13423. /**
  13424. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13425. */
  13426. Light.prototype.toString = function (fullDetails) {
  13427. var ret = "Name: " + this.name;
  13428. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13429. if (this.animations) {
  13430. for (var i = 0; i < this.animations.length; i++) {
  13431. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13432. }
  13433. }
  13434. if (fullDetails) {
  13435. }
  13436. return ret;
  13437. };
  13438. /**
  13439. * Set the enabled state of this node.
  13440. * @param {boolean} value - the new enabled state
  13441. * @see isEnabled
  13442. */
  13443. Light.prototype.setEnabled = function (value) {
  13444. _super.prototype.setEnabled.call(this, value);
  13445. this._resyncMeshes();
  13446. };
  13447. /**
  13448. * Returns the Light associated shadow generator.
  13449. */
  13450. Light.prototype.getShadowGenerator = function () {
  13451. return this._shadowGenerator;
  13452. };
  13453. /**
  13454. * Returns a Vector3, the absolute light position in the World.
  13455. */
  13456. Light.prototype.getAbsolutePosition = function () {
  13457. return BABYLON.Vector3.Zero();
  13458. };
  13459. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13460. };
  13461. Light.prototype._getWorldMatrix = function () {
  13462. return BABYLON.Matrix.Identity();
  13463. };
  13464. /**
  13465. * Boolean : True if the light will affect the passed mesh.
  13466. */
  13467. Light.prototype.canAffectMesh = function (mesh) {
  13468. if (!mesh) {
  13469. return true;
  13470. }
  13471. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13472. return false;
  13473. }
  13474. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13475. return false;
  13476. }
  13477. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13478. return false;
  13479. }
  13480. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13481. return false;
  13482. }
  13483. return true;
  13484. };
  13485. /**
  13486. * Returns the light World matrix.
  13487. */
  13488. Light.prototype.getWorldMatrix = function () {
  13489. this._currentRenderId = this.getScene().getRenderId();
  13490. var worldMatrix = this._getWorldMatrix();
  13491. if (this.parent && this.parent.getWorldMatrix) {
  13492. if (!this._parentedWorldMatrix) {
  13493. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13494. }
  13495. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13496. this._markSyncedWithParent();
  13497. return this._parentedWorldMatrix;
  13498. }
  13499. return worldMatrix;
  13500. };
  13501. /**
  13502. * Sort function to order lights for rendering.
  13503. * @param a First Light object to compare to second.
  13504. * @param b Second Light object to compare first.
  13505. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13506. */
  13507. Light.compareLightsPriority = function (a, b) {
  13508. //shadow-casting lights have priority over non-shadow-casting lights
  13509. //the renderPrioirty is a secondary sort criterion
  13510. if (a.shadowEnabled !== b.shadowEnabled) {
  13511. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13512. }
  13513. return b.renderPriority - a.renderPriority;
  13514. };
  13515. /**
  13516. * Disposes the light.
  13517. */
  13518. Light.prototype.dispose = function () {
  13519. if (this._shadowGenerator) {
  13520. this._shadowGenerator.dispose();
  13521. this._shadowGenerator = null;
  13522. }
  13523. // Animations
  13524. this.getScene().stopAnimation(this);
  13525. // Remove from meshes
  13526. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13527. var mesh = _a[_i];
  13528. mesh._removeLightSource(this);
  13529. }
  13530. this._uniformBuffer.dispose();
  13531. // Remove from scene
  13532. this.getScene().removeLight(this);
  13533. _super.prototype.dispose.call(this);
  13534. };
  13535. /**
  13536. * Returns the light type ID (integer).
  13537. */
  13538. Light.prototype.getTypeID = function () {
  13539. return 0;
  13540. };
  13541. /**
  13542. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13543. */
  13544. Light.prototype.getScaledIntensity = function () {
  13545. return this._photometricScale * this.intensity;
  13546. };
  13547. /**
  13548. * Returns a new Light object, named "name", from the current one.
  13549. */
  13550. Light.prototype.clone = function (name) {
  13551. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13552. };
  13553. /**
  13554. * Serializes the current light into a Serialization object.
  13555. * Returns the serialized object.
  13556. */
  13557. Light.prototype.serialize = function () {
  13558. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13559. // Type
  13560. serializationObject.type = this.getTypeID();
  13561. // Parent
  13562. if (this.parent) {
  13563. serializationObject.parentId = this.parent.id;
  13564. }
  13565. // Inclusion / exclusions
  13566. if (this.excludedMeshes.length > 0) {
  13567. serializationObject.excludedMeshesIds = [];
  13568. this.excludedMeshes.forEach(function (mesh) {
  13569. serializationObject.excludedMeshesIds.push(mesh.id);
  13570. });
  13571. }
  13572. if (this.includedOnlyMeshes.length > 0) {
  13573. serializationObject.includedOnlyMeshesIds = [];
  13574. this.includedOnlyMeshes.forEach(function (mesh) {
  13575. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13576. });
  13577. }
  13578. // Animations
  13579. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13580. serializationObject.ranges = this.serializeAnimationRanges();
  13581. return serializationObject;
  13582. };
  13583. /**
  13584. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13585. * This new light is named "name" and added to the passed scene.
  13586. */
  13587. Light.GetConstructorFromName = function (type, name, scene) {
  13588. switch (type) {
  13589. case 0:
  13590. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13591. case 1:
  13592. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13593. case 2:
  13594. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13595. case 3:
  13596. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13597. }
  13598. };
  13599. /**
  13600. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13601. */
  13602. Light.Parse = function (parsedLight, scene) {
  13603. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13604. // Inclusion / exclusions
  13605. if (parsedLight.excludedMeshesIds) {
  13606. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13607. }
  13608. if (parsedLight.includedOnlyMeshesIds) {
  13609. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13610. }
  13611. // Parent
  13612. if (parsedLight.parentId) {
  13613. light._waitingParentId = parsedLight.parentId;
  13614. }
  13615. // Animations
  13616. if (parsedLight.animations) {
  13617. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13618. var parsedAnimation = parsedLight.animations[animationIndex];
  13619. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13620. }
  13621. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13622. }
  13623. if (parsedLight.autoAnimate) {
  13624. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13625. }
  13626. return light;
  13627. };
  13628. Light.prototype._hookArrayForExcluded = function (array) {
  13629. var _this = this;
  13630. var oldPush = array.push;
  13631. array.push = function () {
  13632. var items = [];
  13633. for (var _i = 0; _i < arguments.length; _i++) {
  13634. items[_i] = arguments[_i];
  13635. }
  13636. var result = oldPush.apply(array, items);
  13637. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13638. var item = items_1[_a];
  13639. item._resyncLighSource(_this);
  13640. }
  13641. return result;
  13642. };
  13643. var oldSplice = array.splice;
  13644. array.splice = function (index, deleteCount) {
  13645. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13646. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13647. var item = deleted_1[_i];
  13648. item._resyncLighSource(_this);
  13649. }
  13650. return deleted;
  13651. };
  13652. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13653. var item = array_1[_i];
  13654. item._resyncLighSource(this);
  13655. }
  13656. };
  13657. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13658. var _this = this;
  13659. var oldPush = array.push;
  13660. array.push = function () {
  13661. var items = [];
  13662. for (var _i = 0; _i < arguments.length; _i++) {
  13663. items[_i] = arguments[_i];
  13664. }
  13665. var result = oldPush.apply(array, items);
  13666. _this._resyncMeshes();
  13667. return result;
  13668. };
  13669. var oldSplice = array.splice;
  13670. array.splice = function (index, deleteCount) {
  13671. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13672. _this._resyncMeshes();
  13673. return deleted;
  13674. };
  13675. this._resyncMeshes();
  13676. };
  13677. Light.prototype._resyncMeshes = function () {
  13678. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13679. var mesh = _a[_i];
  13680. mesh._resyncLighSource(this);
  13681. }
  13682. };
  13683. Light.prototype._markMeshesAsLightDirty = function () {
  13684. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13685. var mesh = _a[_i];
  13686. if (mesh._lightSources.indexOf(this) !== -1) {
  13687. mesh._markSubMeshesAsLightDirty();
  13688. }
  13689. }
  13690. };
  13691. /**
  13692. * Recomputes the cached photometric scale if needed.
  13693. */
  13694. Light.prototype._computePhotometricScale = function () {
  13695. this._photometricScale = this._getPhotometricScale();
  13696. this.getScene().resetCachedMaterial();
  13697. };
  13698. /**
  13699. * Returns the Photometric Scale according to the light type and intensity mode.
  13700. */
  13701. Light.prototype._getPhotometricScale = function () {
  13702. var photometricScale = 0.0;
  13703. var lightTypeID = this.getTypeID();
  13704. //get photometric mode
  13705. var photometricMode = this.intensityMode;
  13706. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13707. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13708. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13709. }
  13710. else {
  13711. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13712. }
  13713. }
  13714. //compute photometric scale
  13715. switch (lightTypeID) {
  13716. case Light.LIGHTTYPEID_POINTLIGHT:
  13717. case Light.LIGHTTYPEID_SPOTLIGHT:
  13718. switch (photometricMode) {
  13719. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13720. photometricScale = 1.0 / (4.0 * Math.PI);
  13721. break;
  13722. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13723. photometricScale = 1.0;
  13724. break;
  13725. case Light.INTENSITYMODE_LUMINANCE:
  13726. photometricScale = this.radius * this.radius;
  13727. break;
  13728. }
  13729. break;
  13730. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13731. switch (photometricMode) {
  13732. case Light.INTENSITYMODE_ILLUMINANCE:
  13733. photometricScale = 1.0;
  13734. break;
  13735. case Light.INTENSITYMODE_LUMINANCE:
  13736. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13737. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13738. var apexAngleRadians = this.radius;
  13739. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13740. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13741. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13742. photometricScale = solidAngle;
  13743. break;
  13744. }
  13745. break;
  13746. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13747. // No fall off in hemisperic light.
  13748. photometricScale = 1.0;
  13749. break;
  13750. }
  13751. return photometricScale;
  13752. };
  13753. Light.prototype._reorderLightsInScene = function () {
  13754. var scene = this.getScene();
  13755. if (this.renderPriority != 0) {
  13756. scene.requireLightSorting = true;
  13757. }
  13758. this.getScene().sortLightsByPriority();
  13759. };
  13760. return Light;
  13761. }(BABYLON.Node));
  13762. //lightmapMode Consts
  13763. Light._LIGHTMAP_DEFAULT = 0;
  13764. Light._LIGHTMAP_SPECULAR = 1;
  13765. Light._LIGHTMAP_SHADOWSONLY = 2;
  13766. // Intensity Mode Consts
  13767. Light._INTENSITYMODE_AUTOMATIC = 0;
  13768. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13769. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13770. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13771. Light._INTENSITYMODE_LUMINANCE = 4;
  13772. // Light types ids const.
  13773. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13774. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13775. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13776. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13777. __decorate([
  13778. BABYLON.serializeAsColor3()
  13779. ], Light.prototype, "diffuse", void 0);
  13780. __decorate([
  13781. BABYLON.serializeAsColor3()
  13782. ], Light.prototype, "specular", void 0);
  13783. __decorate([
  13784. BABYLON.serialize()
  13785. ], Light.prototype, "intensity", void 0);
  13786. __decorate([
  13787. BABYLON.serialize()
  13788. ], Light.prototype, "range", void 0);
  13789. __decorate([
  13790. BABYLON.serialize()
  13791. ], Light.prototype, "intensityMode", null);
  13792. __decorate([
  13793. BABYLON.serialize()
  13794. ], Light.prototype, "radius", null);
  13795. __decorate([
  13796. BABYLON.serialize()
  13797. ], Light.prototype, "_renderPriority", void 0);
  13798. __decorate([
  13799. BABYLON.expandToProperty("_reorderLightsInScene")
  13800. ], Light.prototype, "renderPriority", void 0);
  13801. __decorate([
  13802. BABYLON.serialize()
  13803. ], Light.prototype, "shadowEnabled", void 0);
  13804. __decorate([
  13805. BABYLON.serialize("excludeWithLayerMask")
  13806. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13807. __decorate([
  13808. BABYLON.serialize("includeOnlyWithLayerMask")
  13809. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13810. __decorate([
  13811. BABYLON.serialize("lightmapMode")
  13812. ], Light.prototype, "_lightmapMode", void 0);
  13813. BABYLON.Light = Light;
  13814. })(BABYLON || (BABYLON = {}));
  13815. //# sourceMappingURL=babylon.light.js.map
  13816. var BABYLON;
  13817. (function (BABYLON) {
  13818. var Camera = (function (_super) {
  13819. __extends(Camera, _super);
  13820. function Camera(name, position, scene) {
  13821. var _this = _super.call(this, name, scene) || this;
  13822. _this.upVector = BABYLON.Vector3.Up();
  13823. _this.orthoLeft = null;
  13824. _this.orthoRight = null;
  13825. _this.orthoBottom = null;
  13826. _this.orthoTop = null;
  13827. _this.fov = 0.8;
  13828. _this.minZ = 1.0;
  13829. _this.maxZ = 10000.0;
  13830. _this.inertia = 0.9;
  13831. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13832. _this.isIntermediate = false;
  13833. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13834. _this.layerMask = 0x0FFFFFFF;
  13835. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13836. // Camera rig members
  13837. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13838. _this._rigCameras = new Array();
  13839. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13840. // Cache
  13841. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13842. _this._projectionMatrix = new BABYLON.Matrix();
  13843. _this._doNotComputeProjectionMatrix = false;
  13844. _this._postProcesses = new Array();
  13845. _this._transformMatrix = BABYLON.Matrix.Zero();
  13846. _this._activeMeshes = new BABYLON.SmartArray(256);
  13847. _this._globalPosition = BABYLON.Vector3.Zero();
  13848. _this._refreshFrustumPlanes = true;
  13849. _this.getScene().addCamera(_this);
  13850. if (!_this.getScene().activeCamera) {
  13851. _this.getScene().activeCamera = _this;
  13852. }
  13853. _this.position = position;
  13854. return _this;
  13855. }
  13856. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13857. get: function () {
  13858. return Camera._PERSPECTIVE_CAMERA;
  13859. },
  13860. enumerable: true,
  13861. configurable: true
  13862. });
  13863. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13864. get: function () {
  13865. return Camera._ORTHOGRAPHIC_CAMERA;
  13866. },
  13867. enumerable: true,
  13868. configurable: true
  13869. });
  13870. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13871. get: function () {
  13872. return Camera._FOVMODE_VERTICAL_FIXED;
  13873. },
  13874. enumerable: true,
  13875. configurable: true
  13876. });
  13877. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13878. get: function () {
  13879. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13880. },
  13881. enumerable: true,
  13882. configurable: true
  13883. });
  13884. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13885. get: function () {
  13886. return Camera._RIG_MODE_NONE;
  13887. },
  13888. enumerable: true,
  13889. configurable: true
  13890. });
  13891. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13892. get: function () {
  13893. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13894. },
  13895. enumerable: true,
  13896. configurable: true
  13897. });
  13898. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13899. get: function () {
  13900. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13901. },
  13902. enumerable: true,
  13903. configurable: true
  13904. });
  13905. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13906. get: function () {
  13907. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13908. },
  13909. enumerable: true,
  13910. configurable: true
  13911. });
  13912. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13913. get: function () {
  13914. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13915. },
  13916. enumerable: true,
  13917. configurable: true
  13918. });
  13919. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13920. get: function () {
  13921. return Camera._RIG_MODE_VR;
  13922. },
  13923. enumerable: true,
  13924. configurable: true
  13925. });
  13926. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13927. get: function () {
  13928. return Camera._RIG_MODE_WEBVR;
  13929. },
  13930. enumerable: true,
  13931. configurable: true
  13932. });
  13933. Camera.prototype.getClassName = function () {
  13934. return "Camera";
  13935. };
  13936. /**
  13937. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13938. */
  13939. Camera.prototype.toString = function (fullDetails) {
  13940. var ret = "Name: " + this.name;
  13941. ret += ", type: " + this.getClassName();
  13942. if (this.animations) {
  13943. for (var i = 0; i < this.animations.length; i++) {
  13944. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13945. }
  13946. }
  13947. if (fullDetails) {
  13948. }
  13949. return ret;
  13950. };
  13951. Object.defineProperty(Camera.prototype, "globalPosition", {
  13952. get: function () {
  13953. return this._globalPosition;
  13954. },
  13955. enumerable: true,
  13956. configurable: true
  13957. });
  13958. Camera.prototype.getActiveMeshes = function () {
  13959. return this._activeMeshes;
  13960. };
  13961. Camera.prototype.isActiveMesh = function (mesh) {
  13962. return (this._activeMeshes.indexOf(mesh) !== -1);
  13963. };
  13964. //Cache
  13965. Camera.prototype._initCache = function () {
  13966. _super.prototype._initCache.call(this);
  13967. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13968. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13969. this._cache.mode = undefined;
  13970. this._cache.minZ = undefined;
  13971. this._cache.maxZ = undefined;
  13972. this._cache.fov = undefined;
  13973. this._cache.fovMode = undefined;
  13974. this._cache.aspectRatio = undefined;
  13975. this._cache.orthoLeft = undefined;
  13976. this._cache.orthoRight = undefined;
  13977. this._cache.orthoBottom = undefined;
  13978. this._cache.orthoTop = undefined;
  13979. this._cache.renderWidth = undefined;
  13980. this._cache.renderHeight = undefined;
  13981. };
  13982. Camera.prototype._updateCache = function (ignoreParentClass) {
  13983. if (!ignoreParentClass) {
  13984. _super.prototype._updateCache.call(this);
  13985. }
  13986. var engine = this.getEngine();
  13987. this._cache.position.copyFrom(this.position);
  13988. this._cache.upVector.copyFrom(this.upVector);
  13989. this._cache.mode = this.mode;
  13990. this._cache.minZ = this.minZ;
  13991. this._cache.maxZ = this.maxZ;
  13992. this._cache.fov = this.fov;
  13993. this._cache.fovMode = this.fovMode;
  13994. this._cache.aspectRatio = engine.getAspectRatio(this);
  13995. this._cache.orthoLeft = this.orthoLeft;
  13996. this._cache.orthoRight = this.orthoRight;
  13997. this._cache.orthoBottom = this.orthoBottom;
  13998. this._cache.orthoTop = this.orthoTop;
  13999. this._cache.renderWidth = engine.getRenderWidth();
  14000. this._cache.renderHeight = engine.getRenderHeight();
  14001. };
  14002. Camera.prototype._updateFromScene = function () {
  14003. this.updateCache();
  14004. this.update();
  14005. };
  14006. // Synchronized
  14007. Camera.prototype._isSynchronized = function () {
  14008. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14009. };
  14010. Camera.prototype._isSynchronizedViewMatrix = function () {
  14011. if (!_super.prototype._isSynchronized.call(this))
  14012. return false;
  14013. return this._cache.position.equals(this.position)
  14014. && this._cache.upVector.equals(this.upVector)
  14015. && this.isSynchronizedWithParent();
  14016. };
  14017. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14018. var check = this._cache.mode === this.mode
  14019. && this._cache.minZ === this.minZ
  14020. && this._cache.maxZ === this.maxZ;
  14021. if (!check) {
  14022. return false;
  14023. }
  14024. var engine = this.getEngine();
  14025. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14026. check = this._cache.fov === this.fov
  14027. && this._cache.fovMode === this.fovMode
  14028. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14029. }
  14030. else {
  14031. check = this._cache.orthoLeft === this.orthoLeft
  14032. && this._cache.orthoRight === this.orthoRight
  14033. && this._cache.orthoBottom === this.orthoBottom
  14034. && this._cache.orthoTop === this.orthoTop
  14035. && this._cache.renderWidth === engine.getRenderWidth()
  14036. && this._cache.renderHeight === engine.getRenderHeight();
  14037. }
  14038. return check;
  14039. };
  14040. // Controls
  14041. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14042. };
  14043. Camera.prototype.detachControl = function (element) {
  14044. };
  14045. Camera.prototype.update = function () {
  14046. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14047. this._updateRigCameras();
  14048. }
  14049. this._checkInputs();
  14050. };
  14051. Camera.prototype._checkInputs = function () {
  14052. };
  14053. Object.defineProperty(Camera.prototype, "rigCameras", {
  14054. get: function () {
  14055. return this._rigCameras;
  14056. },
  14057. enumerable: true,
  14058. configurable: true
  14059. });
  14060. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14061. get: function () {
  14062. return this._rigPostProcess;
  14063. },
  14064. enumerable: true,
  14065. configurable: true
  14066. });
  14067. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14068. // invalidate framebuffer
  14069. if (this._postProcesses.length > 0) {
  14070. this._postProcesses[0].markTextureDirty();
  14071. }
  14072. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14073. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14074. var cam = this._rigCameras[i];
  14075. var rigPostProcess = cam._rigPostProcess;
  14076. // for VR rig, there does not have to be a post process
  14077. if (rigPostProcess) {
  14078. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14079. if (isPass) {
  14080. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14081. cam.isIntermediate = this._postProcesses.length === 0;
  14082. }
  14083. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14084. rigPostProcess.markTextureDirty();
  14085. }
  14086. else {
  14087. cam._postProcesses = this._postProcesses.slice(0);
  14088. }
  14089. }
  14090. };
  14091. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14092. if (insertAt === void 0) { insertAt = null; }
  14093. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14094. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14095. return 0;
  14096. }
  14097. if (insertAt == null || insertAt < 0) {
  14098. this._postProcesses.push(postProcess);
  14099. }
  14100. else {
  14101. this._postProcesses.splice(insertAt, 0, postProcess);
  14102. }
  14103. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14104. return this._postProcesses.indexOf(postProcess);
  14105. };
  14106. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14107. if (atIndices === void 0) { atIndices = null; }
  14108. var result = [];
  14109. var i;
  14110. var index;
  14111. if (!atIndices) {
  14112. var idx = this._postProcesses.indexOf(postProcess);
  14113. if (idx !== -1) {
  14114. this._postProcesses.splice(idx, 1);
  14115. }
  14116. }
  14117. else {
  14118. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14119. // iterate descending, so can just splice as we go
  14120. for (i = atIndices.length - 1; i >= 0; i--) {
  14121. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14122. result.push(i);
  14123. continue;
  14124. }
  14125. index = atIndices[i];
  14126. this._postProcesses.splice(index, 1);
  14127. }
  14128. }
  14129. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14130. return result;
  14131. };
  14132. Camera.prototype.getWorldMatrix = function () {
  14133. if (!this._worldMatrix) {
  14134. this._worldMatrix = BABYLON.Matrix.Identity();
  14135. }
  14136. var viewMatrix = this.getViewMatrix();
  14137. viewMatrix.invertToRef(this._worldMatrix);
  14138. return this._worldMatrix;
  14139. };
  14140. Camera.prototype._getViewMatrix = function () {
  14141. return BABYLON.Matrix.Identity();
  14142. };
  14143. Camera.prototype.getViewMatrix = function (force) {
  14144. this._computedViewMatrix = this._computeViewMatrix(force);
  14145. if (!force && this._isSynchronizedViewMatrix()) {
  14146. return this._computedViewMatrix;
  14147. }
  14148. this._refreshFrustumPlanes = true;
  14149. if (!this.parent || !this.parent.getWorldMatrix) {
  14150. this._globalPosition.copyFrom(this.position);
  14151. }
  14152. else {
  14153. if (!this._worldMatrix) {
  14154. this._worldMatrix = BABYLON.Matrix.Identity();
  14155. }
  14156. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14157. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14158. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14159. this._computedViewMatrix.invert();
  14160. this._markSyncedWithParent();
  14161. }
  14162. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14163. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14164. }
  14165. this._currentRenderId = this.getScene().getRenderId();
  14166. return this._computedViewMatrix;
  14167. };
  14168. Camera.prototype._computeViewMatrix = function (force) {
  14169. if (!force && this._isSynchronizedViewMatrix()) {
  14170. return this._computedViewMatrix;
  14171. }
  14172. this._computedViewMatrix = this._getViewMatrix();
  14173. this._currentRenderId = this.getScene().getRenderId();
  14174. return this._computedViewMatrix;
  14175. };
  14176. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14177. this._doNotComputeProjectionMatrix = true;
  14178. if (projection !== undefined) {
  14179. this._projectionMatrix = projection;
  14180. }
  14181. };
  14182. ;
  14183. Camera.prototype.unfreezeProjectionMatrix = function () {
  14184. this._doNotComputeProjectionMatrix = false;
  14185. };
  14186. ;
  14187. Camera.prototype.getProjectionMatrix = function (force) {
  14188. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14189. return this._projectionMatrix;
  14190. }
  14191. this._refreshFrustumPlanes = true;
  14192. var engine = this.getEngine();
  14193. var scene = this.getScene();
  14194. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14195. if (this.minZ <= 0) {
  14196. this.minZ = 0.1;
  14197. }
  14198. if (scene.useRightHandedSystem) {
  14199. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14200. }
  14201. else {
  14202. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14203. }
  14204. return this._projectionMatrix;
  14205. }
  14206. var halfWidth = engine.getRenderWidth() / 2.0;
  14207. var halfHeight = engine.getRenderHeight() / 2.0;
  14208. if (scene.useRightHandedSystem) {
  14209. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14210. }
  14211. else {
  14212. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14213. }
  14214. return this._projectionMatrix;
  14215. };
  14216. Camera.prototype.getTranformationMatrix = function () {
  14217. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14218. return this._transformMatrix;
  14219. };
  14220. Camera.prototype.updateFrustumPlanes = function () {
  14221. if (!this._refreshFrustumPlanes) {
  14222. return;
  14223. }
  14224. this.getTranformationMatrix();
  14225. if (!this._frustumPlanes) {
  14226. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14227. }
  14228. else {
  14229. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14230. }
  14231. this._refreshFrustumPlanes = false;
  14232. };
  14233. Camera.prototype.isInFrustum = function (target) {
  14234. this.updateFrustumPlanes();
  14235. return target.isInFrustum(this._frustumPlanes);
  14236. };
  14237. Camera.prototype.isCompletelyInFrustum = function (target) {
  14238. this.updateFrustumPlanes();
  14239. return target.isCompletelyInFrustum(this._frustumPlanes);
  14240. };
  14241. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14242. if (length === void 0) { length = 100; }
  14243. if (!transform) {
  14244. transform = this.getWorldMatrix();
  14245. }
  14246. if (!origin) {
  14247. origin = this.position;
  14248. }
  14249. var forward = new BABYLON.Vector3(0, 0, 1);
  14250. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14251. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14252. return new BABYLON.Ray(origin, direction, length);
  14253. };
  14254. Camera.prototype.dispose = function () {
  14255. // Animations
  14256. this.getScene().stopAnimation(this);
  14257. // Remove from scene
  14258. this.getScene().removeCamera(this);
  14259. while (this._rigCameras.length > 0) {
  14260. this._rigCameras.pop().dispose();
  14261. }
  14262. // Postprocesses
  14263. var i = this._postProcesses.length;
  14264. while (--i >= 0) {
  14265. this._postProcesses[i].dispose(this);
  14266. }
  14267. _super.prototype.dispose.call(this);
  14268. };
  14269. Object.defineProperty(Camera.prototype, "leftCamera", {
  14270. // ---- Camera rigs section ----
  14271. get: function () {
  14272. if (this._rigCameras.length < 1) {
  14273. return undefined;
  14274. }
  14275. return this._rigCameras[0];
  14276. },
  14277. enumerable: true,
  14278. configurable: true
  14279. });
  14280. Object.defineProperty(Camera.prototype, "rightCamera", {
  14281. get: function () {
  14282. if (this._rigCameras.length < 2) {
  14283. return undefined;
  14284. }
  14285. return this._rigCameras[1];
  14286. },
  14287. enumerable: true,
  14288. configurable: true
  14289. });
  14290. Camera.prototype.getLeftTarget = function () {
  14291. if (this._rigCameras.length < 1) {
  14292. return undefined;
  14293. }
  14294. return this._rigCameras[0].getTarget();
  14295. };
  14296. Camera.prototype.getRightTarget = function () {
  14297. if (this._rigCameras.length < 2) {
  14298. return undefined;
  14299. }
  14300. return this._rigCameras[1].getTarget();
  14301. };
  14302. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14303. while (this._rigCameras.length > 0) {
  14304. this._rigCameras.pop().dispose();
  14305. }
  14306. this.cameraRigMode = mode;
  14307. this._cameraRigParams = {};
  14308. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14309. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14310. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14311. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14312. // create the rig cameras, unless none
  14313. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14314. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14315. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14316. }
  14317. switch (this.cameraRigMode) {
  14318. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14319. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14320. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14321. break;
  14322. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14323. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14324. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14325. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14326. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14327. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14328. break;
  14329. case Camera.RIG_MODE_VR:
  14330. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14331. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14332. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14333. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14334. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14335. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14336. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14337. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14338. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14339. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14340. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14341. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14342. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14343. if (metrics.compensateDistortion) {
  14344. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14345. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14346. }
  14347. break;
  14348. case Camera.RIG_MODE_WEBVR:
  14349. if (rigParams.vrDisplay) {
  14350. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14351. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14352. //Left eye
  14353. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14354. this._rigCameras[0].setCameraRigParameter("left", true);
  14355. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14356. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14357. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14358. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14359. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14360. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14361. this._rigCameras[0].parent = this;
  14362. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14363. //Right eye
  14364. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14365. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14366. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14367. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14368. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14369. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14370. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14371. this._rigCameras[1].parent = this;
  14372. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14373. }
  14374. break;
  14375. }
  14376. this._cascadePostProcessesToRigCams();
  14377. this.
  14378. update();
  14379. };
  14380. Camera.prototype._getVRProjectionMatrix = function () {
  14381. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14382. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14383. return this._projectionMatrix;
  14384. };
  14385. Camera.prototype._updateCameraRotationMatrix = function () {
  14386. //Here for WebVR
  14387. };
  14388. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14389. //Here for WebVR
  14390. };
  14391. /**
  14392. * This function MUST be overwritten by the different WebVR cameras available.
  14393. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14394. */
  14395. Camera.prototype._getWebVRProjectionMatrix = function () {
  14396. return BABYLON.Matrix.Identity();
  14397. };
  14398. /**
  14399. * This function MUST be overwritten by the different WebVR cameras available.
  14400. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14401. */
  14402. Camera.prototype._getWebVRViewMatrix = function () {
  14403. return BABYLON.Matrix.Identity();
  14404. };
  14405. Camera.prototype.setCameraRigParameter = function (name, value) {
  14406. if (!this._cameraRigParams) {
  14407. this._cameraRigParams = {};
  14408. }
  14409. this._cameraRigParams[name] = value;
  14410. //provisionnally:
  14411. if (name === "interaxialDistance") {
  14412. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14413. }
  14414. };
  14415. /**
  14416. * needs to be overridden by children so sub has required properties to be copied
  14417. */
  14418. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14419. return null;
  14420. };
  14421. /**
  14422. * May need to be overridden by children
  14423. */
  14424. Camera.prototype._updateRigCameras = function () {
  14425. for (var i = 0; i < this._rigCameras.length; i++) {
  14426. this._rigCameras[i].minZ = this.minZ;
  14427. this._rigCameras[i].maxZ = this.maxZ;
  14428. this._rigCameras[i].fov = this.fov;
  14429. }
  14430. // only update viewport when ANAGLYPH
  14431. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14432. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14433. }
  14434. };
  14435. Camera.prototype._setupInputs = function () {
  14436. };
  14437. Camera.prototype.serialize = function () {
  14438. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14439. // Type
  14440. serializationObject.type = this.getClassName();
  14441. // Parent
  14442. if (this.parent) {
  14443. serializationObject.parentId = this.parent.id;
  14444. }
  14445. if (this.inputs) {
  14446. this.inputs.serialize(serializationObject);
  14447. }
  14448. // Animations
  14449. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14450. serializationObject.ranges = this.serializeAnimationRanges();
  14451. return serializationObject;
  14452. };
  14453. Camera.prototype.clone = function (name) {
  14454. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14455. };
  14456. Camera.prototype.getDirection = function (localAxis) {
  14457. var result = BABYLON.Vector3.Zero();
  14458. this.getDirectionToRef(localAxis, result);
  14459. return result;
  14460. };
  14461. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14462. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14463. };
  14464. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14465. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14466. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14467. switch (type) {
  14468. case "ArcRotateCamera":
  14469. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14470. case "DeviceOrientationCamera":
  14471. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14472. case "FollowCamera":
  14473. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14474. case "ArcFollowCamera":
  14475. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14476. case "GamepadCamera":
  14477. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14478. case "TouchCamera":
  14479. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14480. case "VirtualJoysticksCamera":
  14481. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14482. case "WebVRFreeCamera":
  14483. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14484. case "WebVRGamepadCamera":
  14485. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14486. case "VRDeviceOrientationFreeCamera":
  14487. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14488. case "VRDeviceOrientationGamepadCamera":
  14489. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14490. case "AnaglyphArcRotateCamera":
  14491. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14492. case "AnaglyphFreeCamera":
  14493. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14494. case "AnaglyphGamepadCamera":
  14495. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14496. case "AnaglyphUniversalCamera":
  14497. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14498. case "StereoscopicArcRotateCamera":
  14499. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14500. case "StereoscopicFreeCamera":
  14501. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14502. case "StereoscopicGamepadCamera":
  14503. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14504. case "StereoscopicUniversalCamera":
  14505. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14506. case "FreeCamera":
  14507. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14508. default:
  14509. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14510. }
  14511. };
  14512. Camera.Parse = function (parsedCamera, scene) {
  14513. var type = parsedCamera.type;
  14514. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14515. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14516. // Parent
  14517. if (parsedCamera.parentId) {
  14518. camera._waitingParentId = parsedCamera.parentId;
  14519. }
  14520. //If camera has an input manager, let it parse inputs settings
  14521. if (camera.inputs) {
  14522. camera.inputs.parse(parsedCamera);
  14523. camera._setupInputs();
  14524. }
  14525. // Target
  14526. if (parsedCamera.target) {
  14527. if (camera.setTarget) {
  14528. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14529. }
  14530. }
  14531. // Apply 3d rig, when found
  14532. if (parsedCamera.cameraRigMode) {
  14533. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14534. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14535. }
  14536. // Animations
  14537. if (parsedCamera.animations) {
  14538. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14539. var parsedAnimation = parsedCamera.animations[animationIndex];
  14540. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14541. }
  14542. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14543. }
  14544. if (parsedCamera.autoAnimate) {
  14545. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14546. }
  14547. return camera;
  14548. };
  14549. return Camera;
  14550. }(BABYLON.Node));
  14551. // Statics
  14552. Camera._PERSPECTIVE_CAMERA = 0;
  14553. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14554. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14555. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14556. Camera._RIG_MODE_NONE = 0;
  14557. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14558. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14559. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14560. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14561. Camera._RIG_MODE_VR = 20;
  14562. Camera._RIG_MODE_WEBVR = 21;
  14563. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14564. __decorate([
  14565. BABYLON.serializeAsVector3()
  14566. ], Camera.prototype, "position", void 0);
  14567. __decorate([
  14568. BABYLON.serializeAsVector3()
  14569. ], Camera.prototype, "upVector", void 0);
  14570. __decorate([
  14571. BABYLON.serialize()
  14572. ], Camera.prototype, "orthoLeft", void 0);
  14573. __decorate([
  14574. BABYLON.serialize()
  14575. ], Camera.prototype, "orthoRight", void 0);
  14576. __decorate([
  14577. BABYLON.serialize()
  14578. ], Camera.prototype, "orthoBottom", void 0);
  14579. __decorate([
  14580. BABYLON.serialize()
  14581. ], Camera.prototype, "orthoTop", void 0);
  14582. __decorate([
  14583. BABYLON.serialize()
  14584. ], Camera.prototype, "fov", void 0);
  14585. __decorate([
  14586. BABYLON.serialize()
  14587. ], Camera.prototype, "minZ", void 0);
  14588. __decorate([
  14589. BABYLON.serialize()
  14590. ], Camera.prototype, "maxZ", void 0);
  14591. __decorate([
  14592. BABYLON.serialize()
  14593. ], Camera.prototype, "inertia", void 0);
  14594. __decorate([
  14595. BABYLON.serialize()
  14596. ], Camera.prototype, "mode", void 0);
  14597. __decorate([
  14598. BABYLON.serialize()
  14599. ], Camera.prototype, "layerMask", void 0);
  14600. __decorate([
  14601. BABYLON.serialize()
  14602. ], Camera.prototype, "fovMode", void 0);
  14603. __decorate([
  14604. BABYLON.serialize()
  14605. ], Camera.prototype, "cameraRigMode", void 0);
  14606. __decorate([
  14607. BABYLON.serialize()
  14608. ], Camera.prototype, "interaxialDistance", void 0);
  14609. __decorate([
  14610. BABYLON.serialize()
  14611. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14612. BABYLON.Camera = Camera;
  14613. })(BABYLON || (BABYLON = {}));
  14614. //# sourceMappingURL=babylon.camera.js.map
  14615. var BABYLON;
  14616. (function (BABYLON) {
  14617. var RenderingManager = (function () {
  14618. function RenderingManager(scene) {
  14619. this._renderingGroups = new Array();
  14620. this._autoClearDepthStencil = {};
  14621. this._customOpaqueSortCompareFn = {};
  14622. this._customAlphaTestSortCompareFn = {};
  14623. this._customTransparentSortCompareFn = {};
  14624. this._renderinGroupInfo = null;
  14625. this._scene = scene;
  14626. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14627. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14628. }
  14629. }
  14630. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14631. if (depth === void 0) { depth = true; }
  14632. if (stencil === void 0) { stencil = true; }
  14633. if (this._depthStencilBufferAlreadyCleaned) {
  14634. return;
  14635. }
  14636. this._scene.getEngine().clear(null, false, depth, stencil);
  14637. this._depthStencilBufferAlreadyCleaned = true;
  14638. };
  14639. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14640. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14641. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14642. var info = null;
  14643. if (observable) {
  14644. if (!this._renderinGroupInfo) {
  14645. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14646. }
  14647. info = this._renderinGroupInfo;
  14648. info.scene = this._scene;
  14649. info.camera = this._scene.activeCamera;
  14650. }
  14651. // Dispatch sprites
  14652. if (renderSprites) {
  14653. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14654. var manager = this._scene.spriteManagers[index];
  14655. this.dispatchSprites(manager);
  14656. }
  14657. }
  14658. // Render
  14659. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14660. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14661. var renderingGroup = this._renderingGroups[index];
  14662. if (!renderingGroup && !observable)
  14663. continue;
  14664. this._currentIndex = index;
  14665. var renderingGroupMask = 0;
  14666. // Fire PRECLEAR stage
  14667. if (observable) {
  14668. renderingGroupMask = Math.pow(2, index);
  14669. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14670. info.renderingGroupId = index;
  14671. observable.notifyObservers(info, renderingGroupMask);
  14672. }
  14673. // Clear depth/stencil if needed
  14674. if (RenderingManager.AUTOCLEAR) {
  14675. var autoClear = this._autoClearDepthStencil[index];
  14676. if (autoClear && autoClear.autoClear) {
  14677. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14678. }
  14679. }
  14680. if (observable) {
  14681. // Fire PREOPAQUE stage
  14682. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14683. observable.notifyObservers(info, renderingGroupMask);
  14684. // Fire PRETRANSPARENT stage
  14685. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14686. observable.notifyObservers(info, renderingGroupMask);
  14687. }
  14688. if (renderingGroup)
  14689. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14690. // Fire POSTTRANSPARENT stage
  14691. if (observable) {
  14692. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14693. observable.notifyObservers(info, renderingGroupMask);
  14694. }
  14695. }
  14696. };
  14697. RenderingManager.prototype.reset = function () {
  14698. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14699. var renderingGroup = this._renderingGroups[index];
  14700. if (renderingGroup) {
  14701. renderingGroup.prepare();
  14702. }
  14703. }
  14704. };
  14705. RenderingManager.prototype.dispose = function () {
  14706. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14707. var renderingGroup = this._renderingGroups[index];
  14708. if (renderingGroup) {
  14709. renderingGroup.dispose();
  14710. }
  14711. }
  14712. this._renderingGroups.length = 0;
  14713. };
  14714. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14715. if (!this._renderingGroups[renderingGroupId]) {
  14716. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14717. }
  14718. };
  14719. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14720. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14721. this._prepareRenderingGroup(renderingGroupId);
  14722. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14723. };
  14724. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14725. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14726. this._prepareRenderingGroup(renderingGroupId);
  14727. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14728. };
  14729. RenderingManager.prototype.dispatch = function (subMesh) {
  14730. var mesh = subMesh.getMesh();
  14731. var renderingGroupId = mesh.renderingGroupId || 0;
  14732. this._prepareRenderingGroup(renderingGroupId);
  14733. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14734. };
  14735. /**
  14736. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14737. * This allowed control for front to back rendering or reversly depending of the special needs.
  14738. *
  14739. * @param renderingGroupId The rendering group id corresponding to its index
  14740. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14741. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14742. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14743. */
  14744. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14745. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14746. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14747. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14748. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14749. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14750. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14751. if (this._renderingGroups[renderingGroupId]) {
  14752. var group = this._renderingGroups[renderingGroupId];
  14753. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14754. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14755. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14756. }
  14757. };
  14758. /**
  14759. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14760. *
  14761. * @param renderingGroupId The rendering group id corresponding to its index
  14762. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14763. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14764. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14765. */
  14766. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14767. if (depth === void 0) { depth = true; }
  14768. if (stencil === void 0) { stencil = true; }
  14769. this._autoClearDepthStencil[renderingGroupId] = {
  14770. autoClear: autoClearDepthStencil,
  14771. depth: depth,
  14772. stencil: stencil
  14773. };
  14774. };
  14775. return RenderingManager;
  14776. }());
  14777. /**
  14778. * The max id used for rendering groups (not included)
  14779. */
  14780. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14781. /**
  14782. * The min id used for rendering groups (included)
  14783. */
  14784. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14785. /**
  14786. * Used to globally prevent autoclearing scenes.
  14787. */
  14788. RenderingManager.AUTOCLEAR = true;
  14789. BABYLON.RenderingManager = RenderingManager;
  14790. })(BABYLON || (BABYLON = {}));
  14791. //# sourceMappingURL=babylon.renderingManager.js.map
  14792. var BABYLON;
  14793. (function (BABYLON) {
  14794. var RenderingGroup = (function () {
  14795. /**
  14796. * Creates a new rendering group.
  14797. * @param index The rendering group index
  14798. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14799. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14800. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14801. */
  14802. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14803. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14804. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14805. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14806. this.index = index;
  14807. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14808. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14809. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14810. this._particleSystems = new BABYLON.SmartArray(256);
  14811. this._spriteManagers = new BABYLON.SmartArray(256);
  14812. this._edgesRenderers = new BABYLON.SmartArray(16);
  14813. this._scene = scene;
  14814. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14815. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14816. this.transparentSortCompareFn = transparentSortCompareFn;
  14817. }
  14818. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14819. /**
  14820. * Set the opaque sort comparison function.
  14821. * If null the sub meshes will be render in the order they were created
  14822. */
  14823. set: function (value) {
  14824. this._opaqueSortCompareFn = value;
  14825. if (value) {
  14826. this._renderOpaque = this.renderOpaqueSorted;
  14827. }
  14828. else {
  14829. this._renderOpaque = RenderingGroup.renderUnsorted;
  14830. }
  14831. },
  14832. enumerable: true,
  14833. configurable: true
  14834. });
  14835. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14836. /**
  14837. * Set the alpha test sort comparison function.
  14838. * If null the sub meshes will be render in the order they were created
  14839. */
  14840. set: function (value) {
  14841. this._alphaTestSortCompareFn = value;
  14842. if (value) {
  14843. this._renderAlphaTest = this.renderAlphaTestSorted;
  14844. }
  14845. else {
  14846. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14847. }
  14848. },
  14849. enumerable: true,
  14850. configurable: true
  14851. });
  14852. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14853. /**
  14854. * Set the transparent sort comparison function.
  14855. * If null the sub meshes will be render in the order they were created
  14856. */
  14857. set: function (value) {
  14858. if (value) {
  14859. this._transparentSortCompareFn = value;
  14860. }
  14861. else {
  14862. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14863. }
  14864. this._renderTransparent = this.renderTransparentSorted;
  14865. },
  14866. enumerable: true,
  14867. configurable: true
  14868. });
  14869. /**
  14870. * Render all the sub meshes contained in the group.
  14871. * @param customRenderFunction Used to override the default render behaviour of the group.
  14872. * @returns true if rendered some submeshes.
  14873. */
  14874. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14875. if (customRenderFunction) {
  14876. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14877. return;
  14878. }
  14879. var engine = this._scene.getEngine();
  14880. // Opaque
  14881. if (this._opaqueSubMeshes.length !== 0) {
  14882. this._renderOpaque(this._opaqueSubMeshes);
  14883. }
  14884. // Alpha test
  14885. if (this._alphaTestSubMeshes.length !== 0) {
  14886. engine.setAlphaTesting(true);
  14887. this._renderAlphaTest(this._alphaTestSubMeshes);
  14888. engine.setAlphaTesting(false);
  14889. }
  14890. var stencilState = engine.getStencilBuffer();
  14891. engine.setStencilBuffer(false);
  14892. // Sprites
  14893. if (renderSprites) {
  14894. this._renderSprites();
  14895. }
  14896. // Particles
  14897. if (renderParticles) {
  14898. this._renderParticles(activeMeshes);
  14899. }
  14900. if (this.onBeforeTransparentRendering) {
  14901. this.onBeforeTransparentRendering();
  14902. }
  14903. // Transparent
  14904. if (this._transparentSubMeshes.length !== 0) {
  14905. this._renderTransparent(this._transparentSubMeshes);
  14906. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14907. }
  14908. engine.setStencilBuffer(stencilState);
  14909. // Edges
  14910. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14911. this._edgesRenderers.data[edgesRendererIndex].render();
  14912. }
  14913. };
  14914. /**
  14915. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14916. * @param subMeshes The submeshes to render
  14917. */
  14918. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14919. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14920. };
  14921. /**
  14922. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14923. * @param subMeshes The submeshes to render
  14924. */
  14925. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14926. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14927. };
  14928. /**
  14929. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14930. * @param subMeshes The submeshes to render
  14931. */
  14932. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14933. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14934. };
  14935. /**
  14936. * Renders the submeshes in a specified order.
  14937. * @param subMeshes The submeshes to sort before render
  14938. * @param sortCompareFn The comparison function use to sort
  14939. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14940. * @param transparent Specifies to activate blending if true
  14941. */
  14942. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14943. var subIndex = 0;
  14944. var subMesh;
  14945. for (; subIndex < subMeshes.length; subIndex++) {
  14946. subMesh = subMeshes.data[subIndex];
  14947. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14948. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14949. }
  14950. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14951. sortedArray.sort(sortCompareFn);
  14952. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14953. subMesh = sortedArray[subIndex];
  14954. subMesh.render(transparent);
  14955. }
  14956. };
  14957. /**
  14958. * Renders the submeshes in the order they were dispatched (no sort applied).
  14959. * @param subMeshes The submeshes to render
  14960. */
  14961. RenderingGroup.renderUnsorted = function (subMeshes) {
  14962. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14963. var submesh = subMeshes.data[subIndex];
  14964. submesh.render(false);
  14965. }
  14966. };
  14967. /**
  14968. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14969. * are rendered back to front if in the same alpha index.
  14970. *
  14971. * @param a The first submesh
  14972. * @param b The second submesh
  14973. * @returns The result of the comparison
  14974. */
  14975. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14976. // Alpha index first
  14977. if (a._alphaIndex > b._alphaIndex) {
  14978. return 1;
  14979. }
  14980. if (a._alphaIndex < b._alphaIndex) {
  14981. return -1;
  14982. }
  14983. // Then distance to camera
  14984. return RenderingGroup.backToFrontSortCompare(a, b);
  14985. };
  14986. /**
  14987. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14988. * are rendered back to front.
  14989. *
  14990. * @param a The first submesh
  14991. * @param b The second submesh
  14992. * @returns The result of the comparison
  14993. */
  14994. RenderingGroup.backToFrontSortCompare = function (a, b) {
  14995. // Then distance to camera
  14996. if (a._distanceToCamera < b._distanceToCamera) {
  14997. return 1;
  14998. }
  14999. if (a._distanceToCamera > b._distanceToCamera) {
  15000. return -1;
  15001. }
  15002. return 0;
  15003. };
  15004. /**
  15005. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15006. * are rendered front to back (prevent overdraw).
  15007. *
  15008. * @param a The first submesh
  15009. * @param b The second submesh
  15010. * @returns The result of the comparison
  15011. */
  15012. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15013. // Then distance to camera
  15014. if (a._distanceToCamera < b._distanceToCamera) {
  15015. return -1;
  15016. }
  15017. if (a._distanceToCamera > b._distanceToCamera) {
  15018. return 1;
  15019. }
  15020. return 0;
  15021. };
  15022. /**
  15023. * Resets the different lists of submeshes to prepare a new frame.
  15024. */
  15025. RenderingGroup.prototype.prepare = function () {
  15026. this._opaqueSubMeshes.reset();
  15027. this._transparentSubMeshes.reset();
  15028. this._alphaTestSubMeshes.reset();
  15029. this._particleSystems.reset();
  15030. this._spriteManagers.reset();
  15031. this._edgesRenderers.reset();
  15032. };
  15033. RenderingGroup.prototype.dispose = function () {
  15034. this._opaqueSubMeshes.dispose();
  15035. this._transparentSubMeshes.dispose();
  15036. this._alphaTestSubMeshes.dispose();
  15037. this._particleSystems.dispose();
  15038. this._spriteManagers.dispose();
  15039. this._edgesRenderers.dispose();
  15040. };
  15041. /**
  15042. * Inserts the submesh in its correct queue depending on its material.
  15043. * @param subMesh The submesh to dispatch
  15044. */
  15045. RenderingGroup.prototype.dispatch = function (subMesh) {
  15046. var material = subMesh.getMaterial();
  15047. var mesh = subMesh.getMesh();
  15048. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15049. this._transparentSubMeshes.push(subMesh);
  15050. }
  15051. else if (material.needAlphaTesting()) {
  15052. this._alphaTestSubMeshes.push(subMesh);
  15053. }
  15054. else {
  15055. this._opaqueSubMeshes.push(subMesh); // Opaque
  15056. }
  15057. if (mesh._edgesRenderer) {
  15058. this._edgesRenderers.push(mesh._edgesRenderer);
  15059. }
  15060. };
  15061. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15062. this._spriteManagers.push(spriteManager);
  15063. };
  15064. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15065. this._particleSystems.push(particleSystem);
  15066. };
  15067. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15068. if (this._particleSystems.length === 0) {
  15069. return;
  15070. }
  15071. // Particles
  15072. var activeCamera = this._scene.activeCamera;
  15073. this._scene._particlesDuration.beginMonitoring();
  15074. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15075. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15076. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15077. continue;
  15078. }
  15079. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15080. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15081. }
  15082. }
  15083. this._scene._particlesDuration.endMonitoring(false);
  15084. };
  15085. RenderingGroup.prototype._renderSprites = function () {
  15086. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15087. return;
  15088. }
  15089. // Sprites
  15090. var activeCamera = this._scene.activeCamera;
  15091. this._scene._spritesDuration.beginMonitoring();
  15092. for (var id = 0; id < this._spriteManagers.length; id++) {
  15093. var spriteManager = this._spriteManagers.data[id];
  15094. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15095. spriteManager.render();
  15096. }
  15097. }
  15098. this._scene._spritesDuration.endMonitoring(false);
  15099. };
  15100. return RenderingGroup;
  15101. }());
  15102. BABYLON.RenderingGroup = RenderingGroup;
  15103. })(BABYLON || (BABYLON = {}));
  15104. //# sourceMappingURL=babylon.renderingGroup.js.map
  15105. var BABYLON;
  15106. (function (BABYLON) {
  15107. var ClickInfo = (function () {
  15108. function ClickInfo() {
  15109. this._singleClick = false;
  15110. this._doubleClick = false;
  15111. this._hasSwiped = false;
  15112. this._ignore = false;
  15113. }
  15114. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15115. get: function () {
  15116. return this._singleClick;
  15117. },
  15118. set: function (b) {
  15119. this._singleClick = b;
  15120. },
  15121. enumerable: true,
  15122. configurable: true
  15123. });
  15124. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15125. get: function () {
  15126. return this._doubleClick;
  15127. },
  15128. set: function (b) {
  15129. this._doubleClick = b;
  15130. },
  15131. enumerable: true,
  15132. configurable: true
  15133. });
  15134. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15135. get: function () {
  15136. return this._hasSwiped;
  15137. },
  15138. set: function (b) {
  15139. this._hasSwiped = b;
  15140. },
  15141. enumerable: true,
  15142. configurable: true
  15143. });
  15144. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15145. get: function () {
  15146. return this._ignore;
  15147. },
  15148. set: function (b) {
  15149. this._ignore = b;
  15150. },
  15151. enumerable: true,
  15152. configurable: true
  15153. });
  15154. return ClickInfo;
  15155. }());
  15156. var PointerEventTypes = (function () {
  15157. function PointerEventTypes() {
  15158. }
  15159. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15160. get: function () {
  15161. return PointerEventTypes._POINTERDOWN;
  15162. },
  15163. enumerable: true,
  15164. configurable: true
  15165. });
  15166. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15167. get: function () {
  15168. return PointerEventTypes._POINTERUP;
  15169. },
  15170. enumerable: true,
  15171. configurable: true
  15172. });
  15173. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15174. get: function () {
  15175. return PointerEventTypes._POINTERMOVE;
  15176. },
  15177. enumerable: true,
  15178. configurable: true
  15179. });
  15180. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15181. get: function () {
  15182. return PointerEventTypes._POINTERWHEEL;
  15183. },
  15184. enumerable: true,
  15185. configurable: true
  15186. });
  15187. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15188. get: function () {
  15189. return PointerEventTypes._POINTERPICK;
  15190. },
  15191. enumerable: true,
  15192. configurable: true
  15193. });
  15194. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15195. get: function () {
  15196. return PointerEventTypes._POINTERTAP;
  15197. },
  15198. enumerable: true,
  15199. configurable: true
  15200. });
  15201. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15202. get: function () {
  15203. return PointerEventTypes._POINTERDOUBLETAP;
  15204. },
  15205. enumerable: true,
  15206. configurable: true
  15207. });
  15208. return PointerEventTypes;
  15209. }());
  15210. PointerEventTypes._POINTERDOWN = 0x01;
  15211. PointerEventTypes._POINTERUP = 0x02;
  15212. PointerEventTypes._POINTERMOVE = 0x04;
  15213. PointerEventTypes._POINTERWHEEL = 0x08;
  15214. PointerEventTypes._POINTERPICK = 0x10;
  15215. PointerEventTypes._POINTERTAP = 0x20;
  15216. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15217. BABYLON.PointerEventTypes = PointerEventTypes;
  15218. var PointerInfoBase = (function () {
  15219. function PointerInfoBase(type, event) {
  15220. this.type = type;
  15221. this.event = event;
  15222. }
  15223. return PointerInfoBase;
  15224. }());
  15225. BABYLON.PointerInfoBase = PointerInfoBase;
  15226. /**
  15227. * This class is used to store pointer related info for the onPrePointerObservable event.
  15228. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15229. */
  15230. var PointerInfoPre = (function (_super) {
  15231. __extends(PointerInfoPre, _super);
  15232. function PointerInfoPre(type, event, localX, localY) {
  15233. var _this = _super.call(this, type, event) || this;
  15234. _this.skipOnPointerObservable = false;
  15235. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15236. return _this;
  15237. }
  15238. return PointerInfoPre;
  15239. }(PointerInfoBase));
  15240. BABYLON.PointerInfoPre = PointerInfoPre;
  15241. /**
  15242. * This type contains all the data related to a pointer event in Babylon.js.
  15243. * 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.
  15244. */
  15245. var PointerInfo = (function (_super) {
  15246. __extends(PointerInfo, _super);
  15247. function PointerInfo(type, event, pickInfo) {
  15248. var _this = _super.call(this, type, event) || this;
  15249. _this.pickInfo = pickInfo;
  15250. return _this;
  15251. }
  15252. return PointerInfo;
  15253. }(PointerInfoBase));
  15254. BABYLON.PointerInfo = PointerInfo;
  15255. /**
  15256. * This class is used by the onRenderingGroupObservable
  15257. */
  15258. var RenderingGroupInfo = (function () {
  15259. function RenderingGroupInfo() {
  15260. }
  15261. return RenderingGroupInfo;
  15262. }());
  15263. /**
  15264. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15265. * This stage will be fired no matter what
  15266. */
  15267. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15268. /**
  15269. * Called before opaque object are rendered.
  15270. * This stage will be fired only if there's 3D Opaque content to render
  15271. */
  15272. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15273. /**
  15274. * Called after the opaque objects are rendered and before the transparent ones
  15275. * This stage will be fired only if there's 3D transparent content to render
  15276. */
  15277. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15278. /**
  15279. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15280. * This stage will be fired no matter what
  15281. */
  15282. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15283. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15284. /**
  15285. * Represents a scene to be rendered by the engine.
  15286. * @see http://doc.babylonjs.com/page.php?p=21911
  15287. */
  15288. var Scene = (function () {
  15289. /**
  15290. * @constructor
  15291. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15292. */
  15293. function Scene(engine) {
  15294. // Members
  15295. this.autoClear = true;
  15296. this.autoClearDepthAndStencil = true;
  15297. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15298. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15299. this.forceWireframe = false;
  15300. this._forcePointsCloud = false;
  15301. this.forceShowBoundingBoxes = false;
  15302. this.animationsEnabled = true;
  15303. this.constantlyUpdateMeshUnderPointer = false;
  15304. this.hoverCursor = "pointer";
  15305. // Metadata
  15306. this.metadata = null;
  15307. // Events
  15308. /**
  15309. * An event triggered when the scene is disposed.
  15310. * @type {BABYLON.Observable}
  15311. */
  15312. this.onDisposeObservable = new BABYLON.Observable();
  15313. /**
  15314. * An event triggered before rendering the scene
  15315. * @type {BABYLON.Observable}
  15316. */
  15317. this.onBeforeRenderObservable = new BABYLON.Observable();
  15318. /**
  15319. * An event triggered after rendering the scene
  15320. * @type {BABYLON.Observable}
  15321. */
  15322. this.onAfterRenderObservable = new BABYLON.Observable();
  15323. /**
  15324. * An event triggered when the scene is ready
  15325. * @type {BABYLON.Observable}
  15326. */
  15327. this.onReadyObservable = new BABYLON.Observable();
  15328. /**
  15329. * An event triggered before rendering a camera
  15330. * @type {BABYLON.Observable}
  15331. */
  15332. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15333. /**
  15334. * An event triggered after rendering a camera
  15335. * @type {BABYLON.Observable}
  15336. */
  15337. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15338. /**
  15339. * An event triggered when a camera is created
  15340. * @type {BABYLON.Observable}
  15341. */
  15342. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15343. /**
  15344. * An event triggered when a camera is removed
  15345. * @type {BABYLON.Observable}
  15346. */
  15347. this.onCameraRemovedObservable = new BABYLON.Observable();
  15348. /**
  15349. * An event triggered when a light is created
  15350. * @type {BABYLON.Observable}
  15351. */
  15352. this.onNewLightAddedObservable = new BABYLON.Observable();
  15353. /**
  15354. * An event triggered when a light is removed
  15355. * @type {BABYLON.Observable}
  15356. */
  15357. this.onLightRemovedObservable = new BABYLON.Observable();
  15358. /**
  15359. * An event triggered when a geometry is created
  15360. * @type {BABYLON.Observable}
  15361. */
  15362. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15363. /**
  15364. * An event triggered when a geometry is removed
  15365. * @type {BABYLON.Observable}
  15366. */
  15367. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15368. /**
  15369. * An event triggered when a mesh is created
  15370. * @type {BABYLON.Observable}
  15371. */
  15372. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15373. /**
  15374. * An event triggered when a mesh is removed
  15375. * @type {BABYLON.Observable}
  15376. */
  15377. this.onMeshRemovedObservable = new BABYLON.Observable();
  15378. /**
  15379. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15380. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15381. * 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)
  15382. */
  15383. this.onRenderingGroupObservable = new BABYLON.Observable();
  15384. // Animations
  15385. this.animations = [];
  15386. /**
  15387. * 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).
  15388. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15389. */
  15390. this.onPrePointerObservable = new BABYLON.Observable();
  15391. /**
  15392. * Observable event triggered each time an input event is received from the rendering canvas
  15393. */
  15394. this.onPointerObservable = new BABYLON.Observable();
  15395. this._meshPickProceed = false;
  15396. this._previousHasSwiped = false;
  15397. this._currentPickResult = null;
  15398. this._previousPickResult = null;
  15399. this._isButtonPressed = false;
  15400. this._doubleClickOccured = false;
  15401. 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
  15402. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15403. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15404. this._startingPointerTime = 0;
  15405. this._previousStartingPointerTime = 0;
  15406. // Coordinate system
  15407. /**
  15408. * use right-handed coordinate system on this scene.
  15409. * @type {boolean}
  15410. */
  15411. this._useRightHandedSystem = false;
  15412. // Fog
  15413. /**
  15414. * is fog enabled on this scene.
  15415. * @type {boolean}
  15416. */
  15417. this._fogEnabled = true;
  15418. this._fogMode = Scene.FOGMODE_NONE;
  15419. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15420. this.fogDensity = 0.1;
  15421. this.fogStart = 0;
  15422. this.fogEnd = 1000.0;
  15423. // Lights
  15424. /**
  15425. * is shadow enabled on this scene.
  15426. * @type {boolean}
  15427. */
  15428. this._shadowsEnabled = true;
  15429. /**
  15430. * is light enabled on this scene.
  15431. * @type {boolean}
  15432. */
  15433. this._lightsEnabled = true;
  15434. /**
  15435. * All of the lights added to this scene.
  15436. * @see BABYLON.Light
  15437. * @type {BABYLON.Light[]}
  15438. */
  15439. this.lights = new Array();
  15440. // Cameras
  15441. /**
  15442. * All of the cameras added to this scene.
  15443. * @see BABYLON.Camera
  15444. * @type {BABYLON.Camera[]}
  15445. */
  15446. this.cameras = new Array();
  15447. this.activeCameras = new Array();
  15448. // Meshes
  15449. /**
  15450. * All of the (abstract) meshes added to this scene.
  15451. * @see BABYLON.AbstractMesh
  15452. * @type {BABYLON.AbstractMesh[]}
  15453. */
  15454. this.meshes = new Array();
  15455. // Geometries
  15456. this._geometries = new Array();
  15457. this.materials = new Array();
  15458. this.multiMaterials = new Array();
  15459. // Textures
  15460. this._texturesEnabled = true;
  15461. this.textures = new Array();
  15462. // Particles
  15463. this.particlesEnabled = true;
  15464. this.particleSystems = new Array();
  15465. // Sprites
  15466. this.spritesEnabled = true;
  15467. this.spriteManagers = new Array();
  15468. // Layers
  15469. this.layers = new Array();
  15470. this.highlightLayers = new Array();
  15471. // Skeletons
  15472. this._skeletonsEnabled = true;
  15473. this.skeletons = new Array();
  15474. // Morph targets
  15475. this.morphTargetManagers = new Array();
  15476. // Lens flares
  15477. this.lensFlaresEnabled = true;
  15478. this.lensFlareSystems = new Array();
  15479. // Collisions
  15480. this.collisionsEnabled = true;
  15481. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15482. // Postprocesses
  15483. this.postProcessesEnabled = true;
  15484. // Customs render targets
  15485. this.renderTargetsEnabled = true;
  15486. this.dumpNextRenderTargets = false;
  15487. this.customRenderTargets = new Array();
  15488. // Imported meshes
  15489. this.importedMeshesFiles = new Array();
  15490. // Probes
  15491. this.probesEnabled = true;
  15492. this.reflectionProbes = new Array();
  15493. this._actionManagers = new Array();
  15494. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15495. // Procedural textures
  15496. this.proceduralTexturesEnabled = true;
  15497. this._proceduralTextures = new Array();
  15498. this.soundTracks = new Array();
  15499. this._audioEnabled = true;
  15500. this._headphone = false;
  15501. // Performance counters
  15502. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15503. this._totalLightsCounter = new BABYLON.PerfCounter();
  15504. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15505. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15506. this._totalVertices = new BABYLON.PerfCounter();
  15507. this._activeIndices = new BABYLON.PerfCounter();
  15508. this._activeParticles = new BABYLON.PerfCounter();
  15509. this._lastFrameDuration = new BABYLON.PerfCounter();
  15510. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15511. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15512. this._particlesDuration = new BABYLON.PerfCounter();
  15513. this._renderDuration = new BABYLON.PerfCounter();
  15514. this._spritesDuration = new BABYLON.PerfCounter();
  15515. this._activeBones = new BABYLON.PerfCounter();
  15516. this._animationTime = 0;
  15517. this.animationTimeScale = 1;
  15518. this._renderId = 0;
  15519. this._executeWhenReadyTimeoutId = -1;
  15520. this._intermediateRendering = false;
  15521. this._viewUpdateFlag = -1;
  15522. this._projectionUpdateFlag = -1;
  15523. this._toBeDisposed = new BABYLON.SmartArray(256);
  15524. this._pendingData = []; //ANY
  15525. this._activeMeshes = new BABYLON.SmartArray(256);
  15526. this._processedMaterials = new BABYLON.SmartArray(256);
  15527. this._renderTargets = new BABYLON.SmartArray(256);
  15528. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15529. this._activeSkeletons = new BABYLON.SmartArray(32);
  15530. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15531. this._activeAnimatables = new Array();
  15532. this._transformMatrix = BABYLON.Matrix.Zero();
  15533. this.requireLightSorting = false;
  15534. this._uniqueIdCounter = 0;
  15535. this.offscreenRenderTarget = null;
  15536. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15537. this._engine.scenes.push(this);
  15538. this._uid = null;
  15539. this._renderingManager = new BABYLON.RenderingManager(this);
  15540. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15541. if (BABYLON.OutlineRenderer) {
  15542. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15543. }
  15544. this.attachControl();
  15545. if (BABYLON.SoundTrack) {
  15546. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15547. }
  15548. //simplification queue
  15549. if (BABYLON.SimplificationQueue) {
  15550. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15551. }
  15552. //collision coordinator initialization. For now legacy per default.
  15553. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15554. // Uniform Buffer
  15555. this._createUbo();
  15556. }
  15557. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15558. get: function () {
  15559. return Scene._FOGMODE_NONE;
  15560. },
  15561. enumerable: true,
  15562. configurable: true
  15563. });
  15564. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15565. get: function () {
  15566. return Scene._FOGMODE_EXP;
  15567. },
  15568. enumerable: true,
  15569. configurable: true
  15570. });
  15571. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15572. get: function () {
  15573. return Scene._FOGMODE_EXP2;
  15574. },
  15575. enumerable: true,
  15576. configurable: true
  15577. });
  15578. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15579. get: function () {
  15580. return Scene._FOGMODE_LINEAR;
  15581. },
  15582. enumerable: true,
  15583. configurable: true
  15584. });
  15585. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15586. /**
  15587. * Texture used in all pbr material as the reflection texture.
  15588. * As in the majority of the scene they are the same (exception for multi room and so on),
  15589. * this is easier to reference from here than from all the materials.
  15590. */
  15591. get: function () {
  15592. return this._environmentTexture;
  15593. },
  15594. /**
  15595. * Texture used in all pbr material as the reflection texture.
  15596. * As in the majority of the scene they are the same (exception for multi room and so on),
  15597. * this is easier to set here than in all the materials.
  15598. */
  15599. set: function (value) {
  15600. this._environmentTexture = value;
  15601. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15602. },
  15603. enumerable: true,
  15604. configurable: true
  15605. });
  15606. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15607. get: function () {
  15608. return this._forcePointsCloud;
  15609. },
  15610. set: function (value) {
  15611. if (this._forcePointsCloud === value) {
  15612. return;
  15613. }
  15614. this._forcePointsCloud = value;
  15615. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15616. },
  15617. enumerable: true,
  15618. configurable: true
  15619. });
  15620. Object.defineProperty(Scene.prototype, "onDispose", {
  15621. set: function (callback) {
  15622. if (this._onDisposeObserver) {
  15623. this.onDisposeObservable.remove(this._onDisposeObserver);
  15624. }
  15625. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15626. },
  15627. enumerable: true,
  15628. configurable: true
  15629. });
  15630. Object.defineProperty(Scene.prototype, "beforeRender", {
  15631. set: function (callback) {
  15632. if (this._onBeforeRenderObserver) {
  15633. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15634. }
  15635. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15636. },
  15637. enumerable: true,
  15638. configurable: true
  15639. });
  15640. Object.defineProperty(Scene.prototype, "afterRender", {
  15641. set: function (callback) {
  15642. if (this._onAfterRenderObserver) {
  15643. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15644. }
  15645. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15646. },
  15647. enumerable: true,
  15648. configurable: true
  15649. });
  15650. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15651. set: function (callback) {
  15652. if (this._onBeforeCameraRenderObserver) {
  15653. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15654. }
  15655. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15656. },
  15657. enumerable: true,
  15658. configurable: true
  15659. });
  15660. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15661. set: function (callback) {
  15662. if (this._onAfterCameraRenderObserver) {
  15663. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15664. }
  15665. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15666. },
  15667. enumerable: true,
  15668. configurable: true
  15669. });
  15670. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15671. get: function () {
  15672. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15673. },
  15674. enumerable: true,
  15675. configurable: true
  15676. });
  15677. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15678. get: function () {
  15679. return this._useRightHandedSystem;
  15680. },
  15681. set: function (value) {
  15682. if (this._useRightHandedSystem === value) {
  15683. return;
  15684. }
  15685. this._useRightHandedSystem = value;
  15686. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15687. },
  15688. enumerable: true,
  15689. configurable: true
  15690. });
  15691. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15692. get: function () {
  15693. return this._fogEnabled;
  15694. },
  15695. set: function (value) {
  15696. if (this._fogEnabled === value) {
  15697. return;
  15698. }
  15699. this._fogEnabled = value;
  15700. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15701. },
  15702. enumerable: true,
  15703. configurable: true
  15704. });
  15705. Object.defineProperty(Scene.prototype, "fogMode", {
  15706. get: function () {
  15707. return this._fogMode;
  15708. },
  15709. set: function (value) {
  15710. if (this._fogMode === value) {
  15711. return;
  15712. }
  15713. this._fogMode = value;
  15714. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15715. },
  15716. enumerable: true,
  15717. configurable: true
  15718. });
  15719. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15720. get: function () {
  15721. return this._shadowsEnabled;
  15722. },
  15723. set: function (value) {
  15724. if (this._shadowsEnabled === value) {
  15725. return;
  15726. }
  15727. this._shadowsEnabled = value;
  15728. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15729. },
  15730. enumerable: true,
  15731. configurable: true
  15732. });
  15733. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15734. get: function () {
  15735. return this._lightsEnabled;
  15736. },
  15737. set: function (value) {
  15738. if (this._lightsEnabled === value) {
  15739. return;
  15740. }
  15741. this._lightsEnabled = value;
  15742. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15743. },
  15744. enumerable: true,
  15745. configurable: true
  15746. });
  15747. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15748. get: function () {
  15749. if (!this._defaultMaterial) {
  15750. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15751. }
  15752. return this._defaultMaterial;
  15753. },
  15754. set: function (value) {
  15755. this._defaultMaterial = value;
  15756. },
  15757. enumerable: true,
  15758. configurable: true
  15759. });
  15760. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15761. get: function () {
  15762. return this._texturesEnabled;
  15763. },
  15764. set: function (value) {
  15765. if (this._texturesEnabled === value) {
  15766. return;
  15767. }
  15768. this._texturesEnabled = value;
  15769. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15770. },
  15771. enumerable: true,
  15772. configurable: true
  15773. });
  15774. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15775. get: function () {
  15776. return this._skeletonsEnabled;
  15777. },
  15778. set: function (value) {
  15779. if (this._skeletonsEnabled === value) {
  15780. return;
  15781. }
  15782. this._skeletonsEnabled = value;
  15783. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15784. },
  15785. enumerable: true,
  15786. configurable: true
  15787. });
  15788. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15789. get: function () {
  15790. if (!this._postProcessRenderPipelineManager) {
  15791. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15792. }
  15793. return this._postProcessRenderPipelineManager;
  15794. },
  15795. enumerable: true,
  15796. configurable: true
  15797. });
  15798. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15799. get: function () {
  15800. return this._frustumPlanes;
  15801. },
  15802. enumerable: true,
  15803. configurable: true
  15804. });
  15805. Object.defineProperty(Scene.prototype, "debugLayer", {
  15806. // Properties
  15807. get: function () {
  15808. if (!this._debugLayer) {
  15809. this._debugLayer = new BABYLON.DebugLayer(this);
  15810. }
  15811. return this._debugLayer;
  15812. },
  15813. enumerable: true,
  15814. configurable: true
  15815. });
  15816. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15817. get: function () {
  15818. return this._workerCollisions;
  15819. },
  15820. set: function (enabled) {
  15821. if (!BABYLON.CollisionCoordinatorLegacy) {
  15822. return;
  15823. }
  15824. enabled = (enabled && !!Worker);
  15825. this._workerCollisions = enabled;
  15826. if (this.collisionCoordinator) {
  15827. this.collisionCoordinator.destroy();
  15828. }
  15829. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15830. this.collisionCoordinator.init(this);
  15831. },
  15832. enumerable: true,
  15833. configurable: true
  15834. });
  15835. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15836. get: function () {
  15837. return this._selectionOctree;
  15838. },
  15839. enumerable: true,
  15840. configurable: true
  15841. });
  15842. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15843. /**
  15844. * The mesh that is currently under the pointer.
  15845. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15846. */
  15847. get: function () {
  15848. return this._pointerOverMesh;
  15849. },
  15850. enumerable: true,
  15851. configurable: true
  15852. });
  15853. Object.defineProperty(Scene.prototype, "pointerX", {
  15854. /**
  15855. * Current on-screen X position of the pointer
  15856. * @return {number} X position of the pointer
  15857. */
  15858. get: function () {
  15859. return this._pointerX;
  15860. },
  15861. enumerable: true,
  15862. configurable: true
  15863. });
  15864. Object.defineProperty(Scene.prototype, "pointerY", {
  15865. /**
  15866. * Current on-screen Y position of the pointer
  15867. * @return {number} Y position of the pointer
  15868. */
  15869. get: function () {
  15870. return this._pointerY;
  15871. },
  15872. enumerable: true,
  15873. configurable: true
  15874. });
  15875. Scene.prototype.getCachedMaterial = function () {
  15876. return this._cachedMaterial;
  15877. };
  15878. Scene.prototype.getCachedEffect = function () {
  15879. return this._cachedEffect;
  15880. };
  15881. Scene.prototype.getCachedVisibility = function () {
  15882. return this._cachedVisibility;
  15883. };
  15884. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  15885. if (visibility === void 0) { visibility = 0; }
  15886. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  15887. };
  15888. Scene.prototype.getBoundingBoxRenderer = function () {
  15889. if (!this._boundingBoxRenderer) {
  15890. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15891. }
  15892. return this._boundingBoxRenderer;
  15893. };
  15894. Scene.prototype.getOutlineRenderer = function () {
  15895. return this._outlineRenderer;
  15896. };
  15897. Scene.prototype.getEngine = function () {
  15898. return this._engine;
  15899. };
  15900. Scene.prototype.getTotalVertices = function () {
  15901. return this._totalVertices.current;
  15902. };
  15903. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15904. get: function () {
  15905. return this._totalVertices;
  15906. },
  15907. enumerable: true,
  15908. configurable: true
  15909. });
  15910. Scene.prototype.getActiveIndices = function () {
  15911. return this._activeIndices.current;
  15912. };
  15913. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15914. get: function () {
  15915. return this._activeIndices;
  15916. },
  15917. enumerable: true,
  15918. configurable: true
  15919. });
  15920. Scene.prototype.getActiveParticles = function () {
  15921. return this._activeParticles.current;
  15922. };
  15923. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15924. get: function () {
  15925. return this._activeParticles;
  15926. },
  15927. enumerable: true,
  15928. configurable: true
  15929. });
  15930. Scene.prototype.getActiveBones = function () {
  15931. return this._activeBones.current;
  15932. };
  15933. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15934. get: function () {
  15935. return this._activeBones;
  15936. },
  15937. enumerable: true,
  15938. configurable: true
  15939. });
  15940. // Stats
  15941. Scene.prototype.getLastFrameDuration = function () {
  15942. return this._lastFrameDuration.current;
  15943. };
  15944. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15945. get: function () {
  15946. return this._lastFrameDuration;
  15947. },
  15948. enumerable: true,
  15949. configurable: true
  15950. });
  15951. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15952. return this._evaluateActiveMeshesDuration.current;
  15953. };
  15954. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15955. get: function () {
  15956. return this._evaluateActiveMeshesDuration;
  15957. },
  15958. enumerable: true,
  15959. configurable: true
  15960. });
  15961. Scene.prototype.getActiveMeshes = function () {
  15962. return this._activeMeshes;
  15963. };
  15964. Scene.prototype.getRenderTargetsDuration = function () {
  15965. return this._renderTargetsDuration.current;
  15966. };
  15967. Scene.prototype.getRenderDuration = function () {
  15968. return this._renderDuration.current;
  15969. };
  15970. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15971. get: function () {
  15972. return this._renderDuration;
  15973. },
  15974. enumerable: true,
  15975. configurable: true
  15976. });
  15977. Scene.prototype.getParticlesDuration = function () {
  15978. return this._particlesDuration.current;
  15979. };
  15980. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15981. get: function () {
  15982. return this._particlesDuration;
  15983. },
  15984. enumerable: true,
  15985. configurable: true
  15986. });
  15987. Scene.prototype.getSpritesDuration = function () {
  15988. return this._spritesDuration.current;
  15989. };
  15990. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15991. get: function () {
  15992. return this._spritesDuration;
  15993. },
  15994. enumerable: true,
  15995. configurable: true
  15996. });
  15997. Scene.prototype.getAnimationRatio = function () {
  15998. return this._animationRatio;
  15999. };
  16000. Scene.prototype.getRenderId = function () {
  16001. return this._renderId;
  16002. };
  16003. Scene.prototype.incrementRenderId = function () {
  16004. this._renderId++;
  16005. };
  16006. Scene.prototype._updatePointerPosition = function (evt) {
  16007. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16008. this._pointerX = evt.clientX - canvasRect.left;
  16009. this._pointerY = evt.clientY - canvasRect.top;
  16010. this._unTranslatedPointerX = this._pointerX;
  16011. this._unTranslatedPointerY = this._pointerY;
  16012. if (this.cameraToUseForPointers) {
  16013. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16014. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16015. }
  16016. };
  16017. Scene.prototype._createUbo = function () {
  16018. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16019. this._sceneUbo.addUniform("viewProjection", 16);
  16020. this._sceneUbo.addUniform("view", 16);
  16021. };
  16022. // Pointers handling
  16023. /**
  16024. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16025. * @param attachUp defines if you want to attach events to pointerup
  16026. * @param attachDown defines if you want to attach events to pointerdown
  16027. * @param attachMove defines if you want to attach events to pointermove
  16028. */
  16029. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16030. var _this = this;
  16031. if (attachUp === void 0) { attachUp = true; }
  16032. if (attachDown === void 0) { attachDown = true; }
  16033. if (attachMove === void 0) { attachMove = true; }
  16034. this._initActionManager = function (act, clickInfo) {
  16035. if (!_this._meshPickProceed) {
  16036. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16037. _this._currentPickResult = pickResult;
  16038. if (pickResult) {
  16039. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16040. }
  16041. _this._meshPickProceed = true;
  16042. }
  16043. return act;
  16044. };
  16045. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16046. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16047. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16048. btn !== _this._previousButtonPressed) {
  16049. _this._doubleClickOccured = false;
  16050. clickInfo.singleClick = true;
  16051. clickInfo.ignore = false;
  16052. cb(clickInfo, _this._currentPickResult);
  16053. }
  16054. };
  16055. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16056. var clickInfo = new ClickInfo();
  16057. _this._currentPickResult = null;
  16058. var act;
  16059. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16060. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16061. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16062. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16063. act = _this._initActionManager(act, clickInfo);
  16064. if (act)
  16065. checkPicking = act.hasPickTriggers;
  16066. }
  16067. if (checkPicking) {
  16068. var btn = evt.button;
  16069. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16070. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16071. if (!clickInfo.hasSwiped) {
  16072. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16073. if (!checkSingleClickImmediately) {
  16074. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16075. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16076. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16077. act = _this._initActionManager(act, clickInfo);
  16078. if (act)
  16079. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16080. }
  16081. }
  16082. if (checkSingleClickImmediately) {
  16083. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16084. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16085. btn !== _this._previousButtonPressed) {
  16086. clickInfo.singleClick = true;
  16087. cb(clickInfo, _this._currentPickResult);
  16088. }
  16089. }
  16090. else {
  16091. // wait that no double click has been raised during the double click delay
  16092. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16093. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16094. }
  16095. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16096. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16097. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16098. act = _this._initActionManager(act, clickInfo);
  16099. if (act)
  16100. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16101. }
  16102. if (checkDoubleClick) {
  16103. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16104. if (btn === _this._previousButtonPressed &&
  16105. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16106. !_this._doubleClickOccured) {
  16107. // pointer has not moved for 2 clicks, it's a double click
  16108. if (!clickInfo.hasSwiped &&
  16109. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16110. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16111. _this._previousStartingPointerTime = 0;
  16112. _this._doubleClickOccured = true;
  16113. clickInfo.doubleClick = true;
  16114. clickInfo.ignore = false;
  16115. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16116. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16117. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16118. cb(clickInfo, _this._currentPickResult);
  16119. }
  16120. else {
  16121. _this._doubleClickOccured = false;
  16122. _this._previousStartingPointerTime = _this._startingPointerTime;
  16123. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16124. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16125. _this._previousButtonPressed = btn;
  16126. _this._previousHasSwiped = clickInfo.hasSwiped;
  16127. if (Scene.ExclusiveDoubleClickMode) {
  16128. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16129. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16130. }
  16131. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16132. cb(clickInfo, _this._previousPickResult);
  16133. }
  16134. else {
  16135. cb(clickInfo, _this._currentPickResult);
  16136. }
  16137. }
  16138. }
  16139. else {
  16140. _this._doubleClickOccured = false;
  16141. _this._previousStartingPointerTime = _this._startingPointerTime;
  16142. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16143. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16144. _this._previousButtonPressed = btn;
  16145. _this._previousHasSwiped = clickInfo.hasSwiped;
  16146. }
  16147. }
  16148. }
  16149. }
  16150. clickInfo.ignore = true;
  16151. cb(clickInfo, _this._currentPickResult);
  16152. };
  16153. var spritePredicate = function (sprite) {
  16154. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16155. };
  16156. this._onPointerMove = function (evt) {
  16157. _this._updatePointerPosition(evt);
  16158. // PreObservable support
  16159. if (_this.onPrePointerObservable.hasObservers()) {
  16160. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16161. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16162. _this.onPrePointerObservable.notifyObservers(pi, type);
  16163. if (pi.skipOnPointerObservable) {
  16164. return;
  16165. }
  16166. }
  16167. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16168. return;
  16169. }
  16170. var canvas = _this._engine.getRenderingCanvas();
  16171. if (!_this.pointerMovePredicate) {
  16172. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16173. }
  16174. // Meshes
  16175. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16176. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16177. _this.setPointerOverSprite(null);
  16178. _this.setPointerOverMesh(pickResult.pickedMesh);
  16179. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16180. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16181. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16182. }
  16183. else {
  16184. canvas.style.cursor = _this.hoverCursor;
  16185. }
  16186. }
  16187. else {
  16188. canvas.style.cursor = "";
  16189. }
  16190. }
  16191. else {
  16192. _this.setPointerOverMesh(null);
  16193. // Sprites
  16194. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16195. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16196. _this.setPointerOverSprite(pickResult.pickedSprite);
  16197. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16198. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16199. }
  16200. else {
  16201. canvas.style.cursor = _this.hoverCursor;
  16202. }
  16203. }
  16204. else {
  16205. _this.setPointerOverSprite(null);
  16206. // Restore pointer
  16207. canvas.style.cursor = "";
  16208. }
  16209. }
  16210. if (_this.onPointerMove) {
  16211. _this.onPointerMove(evt, pickResult);
  16212. }
  16213. if (_this.onPointerObservable.hasObservers()) {
  16214. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16215. var pi = new PointerInfo(type, evt, pickResult);
  16216. _this.onPointerObservable.notifyObservers(pi, type);
  16217. }
  16218. };
  16219. this._onPointerDown = function (evt) {
  16220. _this._isButtonPressed = true;
  16221. _this._pickedDownMesh = null;
  16222. _this._meshPickProceed = false;
  16223. _this._updatePointerPosition(evt);
  16224. // PreObservable support
  16225. if (_this.onPrePointerObservable.hasObservers()) {
  16226. var type = PointerEventTypes.POINTERDOWN;
  16227. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16228. _this.onPrePointerObservable.notifyObservers(pi, type);
  16229. if (pi.skipOnPointerObservable) {
  16230. return;
  16231. }
  16232. }
  16233. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16234. return;
  16235. }
  16236. _this._startingPointerPosition.x = _this._pointerX;
  16237. _this._startingPointerPosition.y = _this._pointerY;
  16238. _this._startingPointerTime = new Date().getTime();
  16239. if (!_this.pointerDownPredicate) {
  16240. _this.pointerDownPredicate = function (mesh) {
  16241. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16242. };
  16243. }
  16244. // Meshes
  16245. _this._pickedDownMesh = null;
  16246. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16247. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16248. _this._pickedDownMesh = pickResult.pickedMesh;
  16249. var actionManager = pickResult.pickedMesh.actionManager;
  16250. if (actionManager) {
  16251. if (actionManager.hasPickTriggers) {
  16252. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16253. switch (evt.button) {
  16254. case 0:
  16255. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16256. break;
  16257. case 1:
  16258. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16259. break;
  16260. case 2:
  16261. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16262. break;
  16263. }
  16264. }
  16265. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16266. window.setTimeout((function () {
  16267. var _this = this;
  16268. 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);
  16269. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16270. if (this._isButtonPressed &&
  16271. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16272. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16273. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16274. this._startingPointerTime = 0;
  16275. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16276. }
  16277. }
  16278. }).bind(_this), Scene.LongPressDelay);
  16279. }
  16280. }
  16281. }
  16282. if (_this.onPointerDown) {
  16283. _this.onPointerDown(evt, pickResult);
  16284. }
  16285. if (_this.onPointerObservable.hasObservers()) {
  16286. var type = PointerEventTypes.POINTERDOWN;
  16287. var pi = new PointerInfo(type, evt, pickResult);
  16288. _this.onPointerObservable.notifyObservers(pi, type);
  16289. }
  16290. // Sprites
  16291. _this._pickedDownSprite = null;
  16292. if (_this.spriteManagers.length > 0) {
  16293. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16294. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16295. if (pickResult.pickedSprite.actionManager) {
  16296. _this._pickedDownSprite = pickResult.pickedSprite;
  16297. switch (evt.button) {
  16298. case 0:
  16299. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16300. break;
  16301. case 1:
  16302. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16303. break;
  16304. case 2:
  16305. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16306. break;
  16307. }
  16308. if (pickResult.pickedSprite.actionManager) {
  16309. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16310. }
  16311. }
  16312. }
  16313. }
  16314. };
  16315. this._onPointerUp = function (evt) {
  16316. _this._isButtonPressed = false;
  16317. _this._pickedUpMesh = null;
  16318. _this._meshPickProceed = false;
  16319. _this._updatePointerPosition(evt);
  16320. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16321. // PreObservable support
  16322. if (this.onPrePointerObservable.hasObservers()) {
  16323. if (!clickInfo.ignore) {
  16324. if (!clickInfo.hasSwiped) {
  16325. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16326. var type = PointerEventTypes.POINTERTAP;
  16327. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16328. this.onPrePointerObservable.notifyObservers(pi, type);
  16329. if (pi.skipOnPointerObservable) {
  16330. return;
  16331. }
  16332. }
  16333. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16334. var type = PointerEventTypes.POINTERDOUBLETAP;
  16335. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16336. this.onPrePointerObservable.notifyObservers(pi, type);
  16337. if (pi.skipOnPointerObservable) {
  16338. return;
  16339. }
  16340. }
  16341. }
  16342. }
  16343. else {
  16344. var type = PointerEventTypes.POINTERUP;
  16345. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16346. this.onPrePointerObservable.notifyObservers(pi, type);
  16347. if (pi.skipOnPointerObservable) {
  16348. return;
  16349. }
  16350. }
  16351. }
  16352. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16353. return;
  16354. }
  16355. if (!this.pointerUpPredicate) {
  16356. this.pointerUpPredicate = function (mesh) {
  16357. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16358. };
  16359. }
  16360. // Meshes
  16361. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16362. this._initActionManager(null, clickInfo);
  16363. }
  16364. if (!pickResult) {
  16365. pickResult = this._currentPickResult;
  16366. }
  16367. if (pickResult && pickResult && pickResult.pickedMesh) {
  16368. this._pickedUpMesh = pickResult.pickedMesh;
  16369. if (this._pickedDownMesh === this._pickedUpMesh) {
  16370. if (this.onPointerPick) {
  16371. this.onPointerPick(evt, pickResult);
  16372. }
  16373. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16374. var type = PointerEventTypes.POINTERPICK;
  16375. var pi = new PointerInfo(type, evt, pickResult);
  16376. this.onPointerObservable.notifyObservers(pi, type);
  16377. }
  16378. }
  16379. if (pickResult.pickedMesh.actionManager) {
  16380. if (clickInfo.ignore) {
  16381. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16382. }
  16383. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16384. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16385. }
  16386. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16387. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16388. }
  16389. }
  16390. }
  16391. if (this._pickedDownMesh &&
  16392. this._pickedDownMesh.actionManager &&
  16393. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16394. this._pickedDownMesh !== this._pickedUpMesh) {
  16395. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16396. }
  16397. if (this.onPointerUp) {
  16398. this.onPointerUp(evt, pickResult);
  16399. }
  16400. if (this.onPointerObservable.hasObservers()) {
  16401. if (!clickInfo.ignore) {
  16402. if (!clickInfo.hasSwiped) {
  16403. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16404. var type = PointerEventTypes.POINTERTAP;
  16405. var pi = new PointerInfo(type, evt, pickResult);
  16406. this.onPointerObservable.notifyObservers(pi, type);
  16407. }
  16408. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16409. var type = PointerEventTypes.POINTERDOUBLETAP;
  16410. var pi = new PointerInfo(type, evt, pickResult);
  16411. this.onPointerObservable.notifyObservers(pi, type);
  16412. }
  16413. }
  16414. }
  16415. else {
  16416. var type = PointerEventTypes.POINTERUP;
  16417. var pi = new PointerInfo(type, evt, pickResult);
  16418. this.onPointerObservable.notifyObservers(pi, type);
  16419. }
  16420. }
  16421. // Sprites
  16422. if (this.spriteManagers.length > 0) {
  16423. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16424. if (pickResult.hit && pickResult.pickedSprite) {
  16425. if (pickResult.pickedSprite.actionManager) {
  16426. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16427. if (pickResult.pickedSprite.actionManager) {
  16428. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16429. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16430. }
  16431. }
  16432. }
  16433. }
  16434. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16435. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16436. }
  16437. }
  16438. this._previousPickResult = this._currentPickResult;
  16439. }).bind(_this));
  16440. };
  16441. this._onKeyDown = function (evt) {
  16442. if (_this.actionManager) {
  16443. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16444. }
  16445. };
  16446. this._onKeyUp = function (evt) {
  16447. if (_this.actionManager) {
  16448. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16449. }
  16450. };
  16451. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16452. var canvas = this._engine.getRenderingCanvas();
  16453. if (attachMove) {
  16454. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16455. // Wheel
  16456. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16457. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16458. }
  16459. if (attachDown) {
  16460. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16461. }
  16462. if (attachUp) {
  16463. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16464. }
  16465. canvas.tabIndex = 1;
  16466. canvas.addEventListener("keydown", this._onKeyDown, false);
  16467. canvas.addEventListener("keyup", this._onKeyUp, false);
  16468. };
  16469. Scene.prototype.detachControl = function () {
  16470. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16471. var canvas = this._engine.getRenderingCanvas();
  16472. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16473. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16474. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16475. // Wheel
  16476. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16477. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16478. canvas.removeEventListener("keydown", this._onKeyDown);
  16479. canvas.removeEventListener("keyup", this._onKeyUp);
  16480. };
  16481. // Ready
  16482. Scene.prototype.isReady = function () {
  16483. if (this._pendingData.length > 0) {
  16484. return false;
  16485. }
  16486. var index;
  16487. // Geometries
  16488. for (index = 0; index < this._geometries.length; index++) {
  16489. var geometry = this._geometries[index];
  16490. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16491. return false;
  16492. }
  16493. }
  16494. // Meshes
  16495. for (index = 0; index < this.meshes.length; index++) {
  16496. var mesh = this.meshes[index];
  16497. if (!mesh.isEnabled()) {
  16498. continue;
  16499. }
  16500. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16501. continue;
  16502. }
  16503. if (!mesh.isReady()) {
  16504. return false;
  16505. }
  16506. var mat = mesh.material;
  16507. if (mat) {
  16508. if (!mat.isReady(mesh)) {
  16509. return false;
  16510. }
  16511. }
  16512. }
  16513. return true;
  16514. };
  16515. Scene.prototype.resetCachedMaterial = function () {
  16516. this._cachedMaterial = null;
  16517. this._cachedEffect = null;
  16518. this._cachedVisibility = null;
  16519. };
  16520. Scene.prototype.registerBeforeRender = function (func) {
  16521. this.onBeforeRenderObservable.add(func);
  16522. };
  16523. Scene.prototype.unregisterBeforeRender = function (func) {
  16524. this.onBeforeRenderObservable.removeCallback(func);
  16525. };
  16526. Scene.prototype.registerAfterRender = function (func) {
  16527. this.onAfterRenderObservable.add(func);
  16528. };
  16529. Scene.prototype.unregisterAfterRender = function (func) {
  16530. this.onAfterRenderObservable.removeCallback(func);
  16531. };
  16532. Scene.prototype._addPendingData = function (data) {
  16533. this._pendingData.push(data);
  16534. };
  16535. Scene.prototype._removePendingData = function (data) {
  16536. var index = this._pendingData.indexOf(data);
  16537. if (index !== -1) {
  16538. this._pendingData.splice(index, 1);
  16539. }
  16540. };
  16541. Scene.prototype.getWaitingItemsCount = function () {
  16542. return this._pendingData.length;
  16543. };
  16544. /**
  16545. * Registers a function to be executed when the scene is ready.
  16546. * @param {Function} func - the function to be executed.
  16547. */
  16548. Scene.prototype.executeWhenReady = function (func) {
  16549. var _this = this;
  16550. this.onReadyObservable.add(func);
  16551. if (this._executeWhenReadyTimeoutId !== -1) {
  16552. return;
  16553. }
  16554. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16555. _this._checkIsReady();
  16556. }, 150);
  16557. };
  16558. Scene.prototype._checkIsReady = function () {
  16559. var _this = this;
  16560. if (this.isReady()) {
  16561. this.onReadyObservable.notifyObservers(this);
  16562. this.onReadyObservable.clear();
  16563. this._executeWhenReadyTimeoutId = -1;
  16564. return;
  16565. }
  16566. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16567. _this._checkIsReady();
  16568. }, 150);
  16569. };
  16570. // Animations
  16571. /**
  16572. * Will start the animation sequence of a given target
  16573. * @param target - the target
  16574. * @param {number} from - from which frame should animation start
  16575. * @param {number} to - till which frame should animation run.
  16576. * @param {boolean} [loop] - should the animation loop
  16577. * @param {number} [speedRatio] - the speed in which to run the animation
  16578. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16579. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16580. * @return {BABYLON.Animatable} the animatable object created for this animation
  16581. * @see BABYLON.Animatable
  16582. * @see http://doc.babylonjs.com/page.php?p=22081
  16583. */
  16584. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16585. if (speedRatio === void 0) { speedRatio = 1.0; }
  16586. if (from > to && speedRatio > 0) {
  16587. speedRatio *= -1;
  16588. }
  16589. this.stopAnimation(target);
  16590. if (!animatable) {
  16591. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16592. }
  16593. // Local animations
  16594. if (target.animations) {
  16595. animatable.appendAnimations(target, target.animations);
  16596. }
  16597. // Children animations
  16598. if (target.getAnimatables) {
  16599. var animatables = target.getAnimatables();
  16600. for (var index = 0; index < animatables.length; index++) {
  16601. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16602. }
  16603. }
  16604. animatable.reset();
  16605. return animatable;
  16606. };
  16607. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16608. if (speedRatio === undefined) {
  16609. speedRatio = 1.0;
  16610. }
  16611. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16612. return animatable;
  16613. };
  16614. Scene.prototype.getAnimatableByTarget = function (target) {
  16615. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16616. if (this._activeAnimatables[index].target === target) {
  16617. return this._activeAnimatables[index];
  16618. }
  16619. }
  16620. return null;
  16621. };
  16622. Object.defineProperty(Scene.prototype, "Animatables", {
  16623. get: function () {
  16624. return this._activeAnimatables;
  16625. },
  16626. enumerable: true,
  16627. configurable: true
  16628. });
  16629. /**
  16630. * Will stop the animation of the given target
  16631. * @param target - the target
  16632. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16633. * @see beginAnimation
  16634. */
  16635. Scene.prototype.stopAnimation = function (target, animationName) {
  16636. var animatable = this.getAnimatableByTarget(target);
  16637. if (animatable) {
  16638. animatable.stop(animationName);
  16639. }
  16640. };
  16641. Scene.prototype._animate = function () {
  16642. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16643. return;
  16644. }
  16645. // Getting time
  16646. var now = BABYLON.Tools.Now;
  16647. if (!this._animationTimeLast) {
  16648. if (this._pendingData.length > 0) {
  16649. return;
  16650. }
  16651. this._animationTimeLast = now;
  16652. }
  16653. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16654. this._animationTime += deltaTime;
  16655. this._animationTimeLast = now;
  16656. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16657. this._activeAnimatables[index]._animate(this._animationTime);
  16658. }
  16659. };
  16660. // Matrix
  16661. Scene.prototype.getViewMatrix = function () {
  16662. return this._viewMatrix;
  16663. };
  16664. Scene.prototype.getProjectionMatrix = function () {
  16665. return this._projectionMatrix;
  16666. };
  16667. Scene.prototype.getTransformMatrix = function () {
  16668. return this._transformMatrix;
  16669. };
  16670. Scene.prototype.setTransformMatrix = function (view, projection) {
  16671. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16672. return;
  16673. }
  16674. this._viewUpdateFlag = view.updateFlag;
  16675. this._projectionUpdateFlag = projection.updateFlag;
  16676. this._viewMatrix = view;
  16677. this._projectionMatrix = projection;
  16678. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16679. // Update frustum
  16680. if (!this._frustumPlanes) {
  16681. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16682. }
  16683. else {
  16684. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16685. }
  16686. if (this._sceneUbo.useUbo) {
  16687. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16688. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16689. this._sceneUbo.update();
  16690. }
  16691. };
  16692. Scene.prototype.getSceneUniformBuffer = function () {
  16693. return this._sceneUbo;
  16694. };
  16695. // Methods
  16696. Scene.prototype.getUniqueId = function () {
  16697. var result = this._uniqueIdCounter;
  16698. this._uniqueIdCounter++;
  16699. return result;
  16700. };
  16701. Scene.prototype.addMesh = function (newMesh) {
  16702. newMesh.uniqueId = this.getUniqueId();
  16703. var position = this.meshes.push(newMesh);
  16704. //notify the collision coordinator
  16705. if (this.collisionCoordinator) {
  16706. this.collisionCoordinator.onMeshAdded(newMesh);
  16707. }
  16708. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16709. };
  16710. Scene.prototype.removeMesh = function (toRemove) {
  16711. var index = this.meshes.indexOf(toRemove);
  16712. if (index !== -1) {
  16713. // Remove from the scene if mesh found
  16714. this.meshes.splice(index, 1);
  16715. }
  16716. //notify the collision coordinator
  16717. if (this.collisionCoordinator) {
  16718. this.collisionCoordinator.onMeshRemoved(toRemove);
  16719. }
  16720. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16721. return index;
  16722. };
  16723. Scene.prototype.removeSkeleton = function (toRemove) {
  16724. var index = this.skeletons.indexOf(toRemove);
  16725. if (index !== -1) {
  16726. // Remove from the scene if found
  16727. this.skeletons.splice(index, 1);
  16728. }
  16729. return index;
  16730. };
  16731. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16732. var index = this.morphTargetManagers.indexOf(toRemove);
  16733. if (index !== -1) {
  16734. // Remove from the scene if found
  16735. this.morphTargetManagers.splice(index, 1);
  16736. }
  16737. return index;
  16738. };
  16739. Scene.prototype.removeLight = function (toRemove) {
  16740. var index = this.lights.indexOf(toRemove);
  16741. if (index !== -1) {
  16742. // Remove from the scene if mesh found
  16743. this.lights.splice(index, 1);
  16744. this.sortLightsByPriority();
  16745. }
  16746. this.onLightRemovedObservable.notifyObservers(toRemove);
  16747. return index;
  16748. };
  16749. Scene.prototype.removeCamera = function (toRemove) {
  16750. var index = this.cameras.indexOf(toRemove);
  16751. if (index !== -1) {
  16752. // Remove from the scene if mesh found
  16753. this.cameras.splice(index, 1);
  16754. }
  16755. // Remove from activeCameras
  16756. var index2 = this.activeCameras.indexOf(toRemove);
  16757. if (index2 !== -1) {
  16758. // Remove from the scene if mesh found
  16759. this.activeCameras.splice(index2, 1);
  16760. }
  16761. // Reset the activeCamera
  16762. if (this.activeCamera === toRemove) {
  16763. if (this.cameras.length > 0) {
  16764. this.activeCamera = this.cameras[0];
  16765. }
  16766. else {
  16767. this.activeCamera = null;
  16768. }
  16769. }
  16770. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16771. return index;
  16772. };
  16773. Scene.prototype.addLight = function (newLight) {
  16774. newLight.uniqueId = this.getUniqueId();
  16775. this.lights.push(newLight);
  16776. this.sortLightsByPriority();
  16777. this.onNewLightAddedObservable.notifyObservers(newLight);
  16778. };
  16779. Scene.prototype.sortLightsByPriority = function () {
  16780. if (this.requireLightSorting) {
  16781. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16782. }
  16783. };
  16784. Scene.prototype.addCamera = function (newCamera) {
  16785. newCamera.uniqueId = this.getUniqueId();
  16786. var position = this.cameras.push(newCamera);
  16787. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16788. };
  16789. /**
  16790. * Switch active camera
  16791. * @param {Camera} newCamera - new active camera
  16792. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16793. */
  16794. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16795. if (attachControl === void 0) { attachControl = true; }
  16796. var canvas = this._engine.getRenderingCanvas();
  16797. this.activeCamera.detachControl(canvas);
  16798. this.activeCamera = newCamera;
  16799. if (attachControl) {
  16800. newCamera.attachControl(canvas);
  16801. }
  16802. };
  16803. /**
  16804. * sets the active camera of the scene using its ID
  16805. * @param {string} id - the camera's ID
  16806. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16807. * @see activeCamera
  16808. */
  16809. Scene.prototype.setActiveCameraByID = function (id) {
  16810. var camera = this.getCameraByID(id);
  16811. if (camera) {
  16812. this.activeCamera = camera;
  16813. return camera;
  16814. }
  16815. return null;
  16816. };
  16817. /**
  16818. * sets the active camera of the scene using its name
  16819. * @param {string} name - the camera's name
  16820. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16821. * @see activeCamera
  16822. */
  16823. Scene.prototype.setActiveCameraByName = function (name) {
  16824. var camera = this.getCameraByName(name);
  16825. if (camera) {
  16826. this.activeCamera = camera;
  16827. return camera;
  16828. }
  16829. return null;
  16830. };
  16831. /**
  16832. * get a material using its id
  16833. * @param {string} the material's ID
  16834. * @return {BABYLON.Material|null} the material or null if none found.
  16835. */
  16836. Scene.prototype.getMaterialByID = function (id) {
  16837. for (var index = 0; index < this.materials.length; index++) {
  16838. if (this.materials[index].id === id) {
  16839. return this.materials[index];
  16840. }
  16841. }
  16842. return null;
  16843. };
  16844. /**
  16845. * get a material using its name
  16846. * @param {string} the material's name
  16847. * @return {BABYLON.Material|null} the material or null if none found.
  16848. */
  16849. Scene.prototype.getMaterialByName = function (name) {
  16850. for (var index = 0; index < this.materials.length; index++) {
  16851. if (this.materials[index].name === name) {
  16852. return this.materials[index];
  16853. }
  16854. }
  16855. return null;
  16856. };
  16857. Scene.prototype.getLensFlareSystemByName = function (name) {
  16858. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16859. if (this.lensFlareSystems[index].name === name) {
  16860. return this.lensFlareSystems[index];
  16861. }
  16862. }
  16863. return null;
  16864. };
  16865. Scene.prototype.getLensFlareSystemByID = function (id) {
  16866. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16867. if (this.lensFlareSystems[index].id === id) {
  16868. return this.lensFlareSystems[index];
  16869. }
  16870. }
  16871. return null;
  16872. };
  16873. Scene.prototype.getCameraByID = function (id) {
  16874. for (var index = 0; index < this.cameras.length; index++) {
  16875. if (this.cameras[index].id === id) {
  16876. return this.cameras[index];
  16877. }
  16878. }
  16879. return null;
  16880. };
  16881. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16882. for (var index = 0; index < this.cameras.length; index++) {
  16883. if (this.cameras[index].uniqueId === uniqueId) {
  16884. return this.cameras[index];
  16885. }
  16886. }
  16887. return null;
  16888. };
  16889. /**
  16890. * get a camera using its name
  16891. * @param {string} the camera's name
  16892. * @return {BABYLON.Camera|null} the camera or null if none found.
  16893. */
  16894. Scene.prototype.getCameraByName = function (name) {
  16895. for (var index = 0; index < this.cameras.length; index++) {
  16896. if (this.cameras[index].name === name) {
  16897. return this.cameras[index];
  16898. }
  16899. }
  16900. return null;
  16901. };
  16902. /**
  16903. * get a bone using its id
  16904. * @param {string} the bone's id
  16905. * @return {BABYLON.Bone|null} the bone or null if not found
  16906. */
  16907. Scene.prototype.getBoneByID = function (id) {
  16908. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16909. var skeleton = this.skeletons[skeletonIndex];
  16910. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16911. if (skeleton.bones[boneIndex].id === id) {
  16912. return skeleton.bones[boneIndex];
  16913. }
  16914. }
  16915. }
  16916. return null;
  16917. };
  16918. /**
  16919. * get a bone using its id
  16920. * @param {string} the bone's name
  16921. * @return {BABYLON.Bone|null} the bone or null if not found
  16922. */
  16923. Scene.prototype.getBoneByName = function (name) {
  16924. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16925. var skeleton = this.skeletons[skeletonIndex];
  16926. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16927. if (skeleton.bones[boneIndex].name === name) {
  16928. return skeleton.bones[boneIndex];
  16929. }
  16930. }
  16931. }
  16932. return null;
  16933. };
  16934. /**
  16935. * get a light node using its name
  16936. * @param {string} the light's name
  16937. * @return {BABYLON.Light|null} the light or null if none found.
  16938. */
  16939. Scene.prototype.getLightByName = function (name) {
  16940. for (var index = 0; index < this.lights.length; index++) {
  16941. if (this.lights[index].name === name) {
  16942. return this.lights[index];
  16943. }
  16944. }
  16945. return null;
  16946. };
  16947. /**
  16948. * get a light node using its ID
  16949. * @param {string} the light's id
  16950. * @return {BABYLON.Light|null} the light or null if none found.
  16951. */
  16952. Scene.prototype.getLightByID = function (id) {
  16953. for (var index = 0; index < this.lights.length; index++) {
  16954. if (this.lights[index].id === id) {
  16955. return this.lights[index];
  16956. }
  16957. }
  16958. return null;
  16959. };
  16960. /**
  16961. * get a light node using its scene-generated unique ID
  16962. * @param {number} the light's unique id
  16963. * @return {BABYLON.Light|null} the light or null if none found.
  16964. */
  16965. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16966. for (var index = 0; index < this.lights.length; index++) {
  16967. if (this.lights[index].uniqueId === uniqueId) {
  16968. return this.lights[index];
  16969. }
  16970. }
  16971. return null;
  16972. };
  16973. /**
  16974. * get a particle system by id
  16975. * @param id {number} the particle system id
  16976. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16977. */
  16978. Scene.prototype.getParticleSystemByID = function (id) {
  16979. for (var index = 0; index < this.particleSystems.length; index++) {
  16980. if (this.particleSystems[index].id === id) {
  16981. return this.particleSystems[index];
  16982. }
  16983. }
  16984. return null;
  16985. };
  16986. /**
  16987. * get a geometry using its ID
  16988. * @param {string} the geometry's id
  16989. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16990. */
  16991. Scene.prototype.getGeometryByID = function (id) {
  16992. for (var index = 0; index < this._geometries.length; index++) {
  16993. if (this._geometries[index].id === id) {
  16994. return this._geometries[index];
  16995. }
  16996. }
  16997. return null;
  16998. };
  16999. /**
  17000. * add a new geometry to this scene.
  17001. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17002. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17003. * @return {boolean} was the geometry added or not
  17004. */
  17005. Scene.prototype.pushGeometry = function (geometry, force) {
  17006. if (!force && this.getGeometryByID(geometry.id)) {
  17007. return false;
  17008. }
  17009. this._geometries.push(geometry);
  17010. //notify the collision coordinator
  17011. if (this.collisionCoordinator) {
  17012. this.collisionCoordinator.onGeometryAdded(geometry);
  17013. }
  17014. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17015. return true;
  17016. };
  17017. /**
  17018. * Removes an existing geometry
  17019. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17020. * @return {boolean} was the geometry removed or not
  17021. */
  17022. Scene.prototype.removeGeometry = function (geometry) {
  17023. var index = this._geometries.indexOf(geometry);
  17024. if (index > -1) {
  17025. this._geometries.splice(index, 1);
  17026. //notify the collision coordinator
  17027. if (this.collisionCoordinator) {
  17028. this.collisionCoordinator.onGeometryDeleted(geometry);
  17029. }
  17030. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17031. return true;
  17032. }
  17033. return false;
  17034. };
  17035. Scene.prototype.getGeometries = function () {
  17036. return this._geometries;
  17037. };
  17038. /**
  17039. * Get the first added mesh found of a given ID
  17040. * @param {string} id - the id to search for
  17041. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17042. */
  17043. Scene.prototype.getMeshByID = function (id) {
  17044. for (var index = 0; index < this.meshes.length; index++) {
  17045. if (this.meshes[index].id === id) {
  17046. return this.meshes[index];
  17047. }
  17048. }
  17049. return null;
  17050. };
  17051. Scene.prototype.getMeshesByID = function (id) {
  17052. return this.meshes.filter(function (m) {
  17053. return m.id === id;
  17054. });
  17055. };
  17056. /**
  17057. * Get a mesh with its auto-generated unique id
  17058. * @param {number} uniqueId - the unique id to search for
  17059. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17060. */
  17061. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17062. for (var index = 0; index < this.meshes.length; index++) {
  17063. if (this.meshes[index].uniqueId === uniqueId) {
  17064. return this.meshes[index];
  17065. }
  17066. }
  17067. return null;
  17068. };
  17069. /**
  17070. * Get a the last added mesh found of a given ID
  17071. * @param {string} id - the id to search for
  17072. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17073. */
  17074. Scene.prototype.getLastMeshByID = function (id) {
  17075. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17076. if (this.meshes[index].id === id) {
  17077. return this.meshes[index];
  17078. }
  17079. }
  17080. return null;
  17081. };
  17082. /**
  17083. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17084. * @param {string} id - the id to search for
  17085. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17086. */
  17087. Scene.prototype.getLastEntryByID = function (id) {
  17088. var index;
  17089. for (index = this.meshes.length - 1; index >= 0; index--) {
  17090. if (this.meshes[index].id === id) {
  17091. return this.meshes[index];
  17092. }
  17093. }
  17094. for (index = this.cameras.length - 1; index >= 0; index--) {
  17095. if (this.cameras[index].id === id) {
  17096. return this.cameras[index];
  17097. }
  17098. }
  17099. for (index = this.lights.length - 1; index >= 0; index--) {
  17100. if (this.lights[index].id === id) {
  17101. return this.lights[index];
  17102. }
  17103. }
  17104. return null;
  17105. };
  17106. Scene.prototype.getNodeByID = function (id) {
  17107. var mesh = this.getMeshByID(id);
  17108. if (mesh) {
  17109. return mesh;
  17110. }
  17111. var light = this.getLightByID(id);
  17112. if (light) {
  17113. return light;
  17114. }
  17115. var camera = this.getCameraByID(id);
  17116. if (camera) {
  17117. return camera;
  17118. }
  17119. var bone = this.getBoneByID(id);
  17120. return bone;
  17121. };
  17122. Scene.prototype.getNodeByName = function (name) {
  17123. var mesh = this.getMeshByName(name);
  17124. if (mesh) {
  17125. return mesh;
  17126. }
  17127. var light = this.getLightByName(name);
  17128. if (light) {
  17129. return light;
  17130. }
  17131. var camera = this.getCameraByName(name);
  17132. if (camera) {
  17133. return camera;
  17134. }
  17135. var bone = this.getBoneByName(name);
  17136. return bone;
  17137. };
  17138. Scene.prototype.getMeshByName = function (name) {
  17139. for (var index = 0; index < this.meshes.length; index++) {
  17140. if (this.meshes[index].name === name) {
  17141. return this.meshes[index];
  17142. }
  17143. }
  17144. return null;
  17145. };
  17146. Scene.prototype.getSoundByName = function (name) {
  17147. var index;
  17148. if (BABYLON.AudioEngine) {
  17149. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17150. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17151. return this.mainSoundTrack.soundCollection[index];
  17152. }
  17153. }
  17154. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17155. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17156. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17157. return this.soundTracks[sdIndex].soundCollection[index];
  17158. }
  17159. }
  17160. }
  17161. }
  17162. return null;
  17163. };
  17164. Scene.prototype.getLastSkeletonByID = function (id) {
  17165. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17166. if (this.skeletons[index].id === id) {
  17167. return this.skeletons[index];
  17168. }
  17169. }
  17170. return null;
  17171. };
  17172. Scene.prototype.getSkeletonById = function (id) {
  17173. for (var index = 0; index < this.skeletons.length; index++) {
  17174. if (this.skeletons[index].id === id) {
  17175. return this.skeletons[index];
  17176. }
  17177. }
  17178. return null;
  17179. };
  17180. Scene.prototype.getSkeletonByName = function (name) {
  17181. for (var index = 0; index < this.skeletons.length; index++) {
  17182. if (this.skeletons[index].name === name) {
  17183. return this.skeletons[index];
  17184. }
  17185. }
  17186. return null;
  17187. };
  17188. Scene.prototype.getMorphTargetManagerById = function (id) {
  17189. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17190. if (this.morphTargetManagers[index].uniqueId === id) {
  17191. return this.morphTargetManagers[index];
  17192. }
  17193. }
  17194. return null;
  17195. };
  17196. Scene.prototype.isActiveMesh = function (mesh) {
  17197. return (this._activeMeshes.indexOf(mesh) !== -1);
  17198. };
  17199. /**
  17200. * Return a the first highlight layer of the scene with a given name.
  17201. * @param name The name of the highlight layer to look for.
  17202. * @return The highlight layer if found otherwise null.
  17203. */
  17204. Scene.prototype.getHighlightLayerByName = function (name) {
  17205. for (var index = 0; index < this.highlightLayers.length; index++) {
  17206. if (this.highlightLayers[index].name === name) {
  17207. return this.highlightLayers[index];
  17208. }
  17209. }
  17210. return null;
  17211. };
  17212. Object.defineProperty(Scene.prototype, "uid", {
  17213. /**
  17214. * Return a unique id as a string which can serve as an identifier for the scene
  17215. */
  17216. get: function () {
  17217. if (!this._uid) {
  17218. this._uid = BABYLON.Tools.RandomId();
  17219. }
  17220. return this._uid;
  17221. },
  17222. enumerable: true,
  17223. configurable: true
  17224. });
  17225. /**
  17226. * Add an externaly attached data from its key.
  17227. * This method call will fail and return false, if such key already exists.
  17228. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17229. * @param key the unique key that identifies the data
  17230. * @param data the data object to associate to the key for this Engine instance
  17231. * @return true if no such key were already present and the data was added successfully, false otherwise
  17232. */
  17233. Scene.prototype.addExternalData = function (key, data) {
  17234. if (!this._externalData) {
  17235. this._externalData = new BABYLON.StringDictionary();
  17236. }
  17237. return this._externalData.add(key, data);
  17238. };
  17239. /**
  17240. * Get an externaly attached data from its key
  17241. * @param key the unique key that identifies the data
  17242. * @return the associated data, if present (can be null), or undefined if not present
  17243. */
  17244. Scene.prototype.getExternalData = function (key) {
  17245. if (!this._externalData) {
  17246. return null;
  17247. }
  17248. return this._externalData.get(key);
  17249. };
  17250. /**
  17251. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17252. * @param key the unique key that identifies the data
  17253. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17254. * @return the associated data, can be null if the factory returned null.
  17255. */
  17256. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17257. if (!this._externalData) {
  17258. this._externalData = new BABYLON.StringDictionary();
  17259. }
  17260. return this._externalData.getOrAddWithFactory(key, factory);
  17261. };
  17262. /**
  17263. * Remove an externaly attached data from the Engine instance
  17264. * @param key the unique key that identifies the data
  17265. * @return true if the data was successfully removed, false if it doesn't exist
  17266. */
  17267. Scene.prototype.removeExternalData = function (key) {
  17268. return this._externalData.remove(key);
  17269. };
  17270. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17271. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17272. var material = subMesh.getMaterial();
  17273. if (mesh.showSubMeshesBoundingBox) {
  17274. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17275. }
  17276. if (material) {
  17277. // Render targets
  17278. if (material.getRenderTargetTextures) {
  17279. if (this._processedMaterials.indexOf(material) === -1) {
  17280. this._processedMaterials.push(material);
  17281. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17282. }
  17283. }
  17284. // Dispatch
  17285. this._activeIndices.addCount(subMesh.indexCount, false);
  17286. this._renderingManager.dispatch(subMesh);
  17287. }
  17288. }
  17289. };
  17290. Scene.prototype._isInIntermediateRendering = function () {
  17291. return this._intermediateRendering;
  17292. };
  17293. Scene.prototype._evaluateActiveMeshes = function () {
  17294. this.activeCamera._activeMeshes.reset();
  17295. this._activeMeshes.reset();
  17296. this._renderingManager.reset();
  17297. this._processedMaterials.reset();
  17298. this._activeParticleSystems.reset();
  17299. this._activeSkeletons.reset();
  17300. this._softwareSkinnedMeshes.reset();
  17301. if (this._boundingBoxRenderer) {
  17302. this._boundingBoxRenderer.reset();
  17303. }
  17304. // Meshes
  17305. var meshes;
  17306. var len;
  17307. if (this._selectionOctree) {
  17308. var selection = this._selectionOctree.select(this._frustumPlanes);
  17309. meshes = selection.data;
  17310. len = selection.length;
  17311. }
  17312. else {
  17313. len = this.meshes.length;
  17314. meshes = this.meshes;
  17315. }
  17316. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17317. var mesh = meshes[meshIndex];
  17318. if (mesh.isBlocked) {
  17319. continue;
  17320. }
  17321. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17322. if (!mesh.isReady() || !mesh.isEnabled()) {
  17323. continue;
  17324. }
  17325. mesh.computeWorldMatrix();
  17326. // Intersections
  17327. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17328. this._meshesForIntersections.pushNoDuplicate(mesh);
  17329. }
  17330. // Switch to current LOD
  17331. var meshLOD = mesh.getLOD(this.activeCamera);
  17332. if (!meshLOD) {
  17333. continue;
  17334. }
  17335. mesh._preActivate();
  17336. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17337. this._activeMeshes.push(mesh);
  17338. this.activeCamera._activeMeshes.push(mesh);
  17339. mesh._activate(this._renderId);
  17340. this._activeMesh(mesh, meshLOD);
  17341. }
  17342. }
  17343. // Particle systems
  17344. this._particlesDuration.beginMonitoring();
  17345. var beforeParticlesDate = BABYLON.Tools.Now;
  17346. if (this.particlesEnabled) {
  17347. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17348. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17349. var particleSystem = this.particleSystems[particleIndex];
  17350. if (!particleSystem.isStarted()) {
  17351. continue;
  17352. }
  17353. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17354. this._activeParticleSystems.push(particleSystem);
  17355. particleSystem.animate();
  17356. this._renderingManager.dispatchParticles(particleSystem);
  17357. }
  17358. }
  17359. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17360. }
  17361. this._particlesDuration.endMonitoring(false);
  17362. };
  17363. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17364. if (mesh.skeleton && this.skeletonsEnabled) {
  17365. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17366. mesh.skeleton.prepare();
  17367. }
  17368. if (!mesh.computeBonesUsingShaders) {
  17369. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17370. }
  17371. }
  17372. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17373. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17374. }
  17375. if (mesh && mesh.subMeshes) {
  17376. // Submeshes Octrees
  17377. var len;
  17378. var subMeshes;
  17379. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17380. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17381. len = intersections.length;
  17382. subMeshes = intersections.data;
  17383. }
  17384. else {
  17385. subMeshes = mesh.subMeshes;
  17386. len = subMeshes.length;
  17387. }
  17388. for (var subIndex = 0; subIndex < len; subIndex++) {
  17389. var subMesh = subMeshes[subIndex];
  17390. this._evaluateSubMesh(subMesh, mesh);
  17391. }
  17392. }
  17393. };
  17394. Scene.prototype.updateTransformMatrix = function (force) {
  17395. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17396. };
  17397. Scene.prototype._renderForCamera = function (camera) {
  17398. var engine = this._engine;
  17399. var startTime = BABYLON.Tools.Now;
  17400. this.activeCamera = camera;
  17401. if (!this.activeCamera)
  17402. throw new Error("Active camera not set");
  17403. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17404. // Viewport
  17405. engine.setViewport(this.activeCamera.viewport);
  17406. // Camera
  17407. this.resetCachedMaterial();
  17408. this._renderId++;
  17409. this.updateTransformMatrix();
  17410. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17411. // Meshes
  17412. this._evaluateActiveMeshesDuration.beginMonitoring();
  17413. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17414. this._evaluateActiveMeshes();
  17415. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17416. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17417. // Software skinning
  17418. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17419. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17420. mesh.applySkeleton(mesh.skeleton);
  17421. }
  17422. // Render targets
  17423. this._renderTargetsDuration.beginMonitoring();
  17424. var needsRestoreFrameBuffer = false;
  17425. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17426. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17427. this._intermediateRendering = true;
  17428. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17429. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17430. var renderTarget = this._renderTargets.data[renderIndex];
  17431. if (renderTarget._shouldRender()) {
  17432. this._renderId++;
  17433. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17434. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17435. }
  17436. }
  17437. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17438. this._intermediateRendering = false;
  17439. this._renderId++;
  17440. needsRestoreFrameBuffer = true; // Restore back buffer
  17441. }
  17442. // Render HighlightLayer Texture
  17443. var stencilState = this._engine.getStencilBuffer();
  17444. var renderhighlights = false;
  17445. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17446. this._intermediateRendering = true;
  17447. for (var i = 0; i < this.highlightLayers.length; i++) {
  17448. var highlightLayer = this.highlightLayers[i];
  17449. if (highlightLayer.shouldRender() &&
  17450. (!highlightLayer.camera ||
  17451. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17452. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17453. renderhighlights = true;
  17454. var renderTarget = highlightLayer._mainTexture;
  17455. if (renderTarget._shouldRender()) {
  17456. this._renderId++;
  17457. renderTarget.render(false, false);
  17458. needsRestoreFrameBuffer = true;
  17459. }
  17460. }
  17461. }
  17462. this._intermediateRendering = false;
  17463. this._renderId++;
  17464. }
  17465. if (needsRestoreFrameBuffer) {
  17466. if (this.offscreenRenderTarget) {
  17467. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17468. }
  17469. else {
  17470. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17471. }
  17472. }
  17473. this._renderTargetsDuration.endMonitoring(false);
  17474. // Prepare Frame
  17475. this.postProcessManager._prepareFrame();
  17476. this._renderDuration.beginMonitoring();
  17477. // Backgrounds
  17478. var layerIndex;
  17479. var layer;
  17480. if (this.layers.length) {
  17481. engine.setDepthBuffer(false);
  17482. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17483. layer = this.layers[layerIndex];
  17484. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17485. layer.render();
  17486. }
  17487. }
  17488. engine.setDepthBuffer(true);
  17489. }
  17490. // Render
  17491. BABYLON.Tools.StartPerformanceCounter("Main render");
  17492. // Activate HighlightLayer stencil
  17493. if (renderhighlights) {
  17494. this._engine.setStencilBuffer(true);
  17495. }
  17496. this._renderingManager.render(null, null, true, true);
  17497. // Restore HighlightLayer stencil
  17498. if (renderhighlights) {
  17499. this._engine.setStencilBuffer(stencilState);
  17500. }
  17501. BABYLON.Tools.EndPerformanceCounter("Main render");
  17502. // Bounding boxes
  17503. if (this._boundingBoxRenderer) {
  17504. this._boundingBoxRenderer.render();
  17505. }
  17506. // Lens flares
  17507. if (this.lensFlaresEnabled) {
  17508. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17509. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17510. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17511. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17512. lensFlareSystem.render();
  17513. }
  17514. }
  17515. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17516. }
  17517. // Foregrounds
  17518. if (this.layers.length) {
  17519. engine.setDepthBuffer(false);
  17520. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17521. layer = this.layers[layerIndex];
  17522. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17523. layer.render();
  17524. }
  17525. }
  17526. engine.setDepthBuffer(true);
  17527. }
  17528. // Highlight Layer
  17529. if (renderhighlights) {
  17530. engine.setDepthBuffer(false);
  17531. for (var i = 0; i < this.highlightLayers.length; i++) {
  17532. if (this.highlightLayers[i].shouldRender()) {
  17533. this.highlightLayers[i].render();
  17534. }
  17535. }
  17536. engine.setDepthBuffer(true);
  17537. }
  17538. this._renderDuration.endMonitoring(false);
  17539. // Finalize frame
  17540. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17541. // Update camera
  17542. this.activeCamera._updateFromScene();
  17543. // Reset some special arrays
  17544. this._renderTargets.reset();
  17545. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17546. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17547. };
  17548. Scene.prototype._processSubCameras = function (camera) {
  17549. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17550. this._renderForCamera(camera);
  17551. return;
  17552. }
  17553. // rig cameras
  17554. for (var index = 0; index < camera._rigCameras.length; index++) {
  17555. this._renderForCamera(camera._rigCameras[index]);
  17556. }
  17557. this.activeCamera = camera;
  17558. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17559. // Update camera
  17560. this.activeCamera._updateFromScene();
  17561. };
  17562. Scene.prototype._checkIntersections = function () {
  17563. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17564. var sourceMesh = this._meshesForIntersections.data[index];
  17565. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17566. var action = sourceMesh.actionManager.actions[actionIndex];
  17567. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17568. var parameters = action.getTriggerParameter();
  17569. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17570. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17571. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17572. if (areIntersecting && currentIntersectionInProgress === -1) {
  17573. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17574. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17575. sourceMesh._intersectionsInProgress.push(otherMesh);
  17576. }
  17577. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17578. sourceMesh._intersectionsInProgress.push(otherMesh);
  17579. }
  17580. }
  17581. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17582. //They intersected, and now they don't.
  17583. //is this trigger an exit trigger? execute an event.
  17584. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17585. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17586. }
  17587. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17588. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17589. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17590. }
  17591. }
  17592. }
  17593. }
  17594. }
  17595. };
  17596. Scene.prototype.render = function () {
  17597. if (this.isDisposed) {
  17598. return;
  17599. }
  17600. this._lastFrameDuration.beginMonitoring();
  17601. this._particlesDuration.fetchNewFrame();
  17602. this._spritesDuration.fetchNewFrame();
  17603. this._activeParticles.fetchNewFrame();
  17604. this._renderDuration.fetchNewFrame();
  17605. this._renderTargetsDuration.fetchNewFrame();
  17606. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17607. this._totalVertices.fetchNewFrame();
  17608. this._activeIndices.fetchNewFrame();
  17609. this._activeBones.fetchNewFrame();
  17610. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17611. this._meshesForIntersections.reset();
  17612. this.resetCachedMaterial();
  17613. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17614. // Actions
  17615. if (this.actionManager) {
  17616. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17617. }
  17618. //Simplification Queue
  17619. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17620. this.simplificationQueue.executeNext();
  17621. }
  17622. // Animations
  17623. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17624. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17625. this._animate();
  17626. // Physics
  17627. if (this._physicsEngine) {
  17628. BABYLON.Tools.StartPerformanceCounter("Physics");
  17629. this._physicsEngine._step(deltaTime / 1000.0);
  17630. BABYLON.Tools.EndPerformanceCounter("Physics");
  17631. }
  17632. // Before render
  17633. this.onBeforeRenderObservable.notifyObservers(this);
  17634. // Customs render targets
  17635. this._renderTargetsDuration.beginMonitoring();
  17636. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17637. var engine = this.getEngine();
  17638. var currentActiveCamera = this.activeCamera;
  17639. if (this.renderTargetsEnabled) {
  17640. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17641. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17642. var renderTarget = this.customRenderTargets[customIndex];
  17643. if (renderTarget._shouldRender()) {
  17644. this._renderId++;
  17645. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17646. if (!this.activeCamera)
  17647. throw new Error("Active camera not set");
  17648. // Viewport
  17649. engine.setViewport(this.activeCamera.viewport);
  17650. // Camera
  17651. this.updateTransformMatrix();
  17652. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17653. }
  17654. }
  17655. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17656. this._renderId++;
  17657. }
  17658. if (this.offscreenRenderTarget) {
  17659. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17660. }
  17661. else {
  17662. // Restore back buffer
  17663. if (this.customRenderTargets.length > 0) {
  17664. engine.restoreDefaultFramebuffer();
  17665. }
  17666. }
  17667. this._renderTargetsDuration.endMonitoring();
  17668. this.activeCamera = currentActiveCamera;
  17669. // Procedural textures
  17670. if (this.proceduralTexturesEnabled) {
  17671. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17672. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17673. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17674. if (proceduralTexture._shouldRender()) {
  17675. proceduralTexture.render();
  17676. }
  17677. }
  17678. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17679. }
  17680. // Clear
  17681. if (this.autoClearDepthAndStencil || this.autoClear) {
  17682. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17683. }
  17684. // Shadows
  17685. if (this.shadowsEnabled) {
  17686. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17687. var light = this.lights[lightIndex];
  17688. var shadowGenerator = light.getShadowGenerator();
  17689. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17690. var shadowMap = shadowGenerator.getShadowMap();
  17691. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17692. this._renderTargets.push(shadowMap);
  17693. }
  17694. }
  17695. }
  17696. }
  17697. // Depth renderer
  17698. if (this._depthRenderer) {
  17699. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17700. }
  17701. // Geometry renderer
  17702. if (this._geometryBufferRenderer) {
  17703. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17704. }
  17705. // RenderPipeline
  17706. if (this._postProcessRenderPipelineManager) {
  17707. this._postProcessRenderPipelineManager.update();
  17708. }
  17709. // Multi-cameras?
  17710. if (this.activeCameras.length > 0) {
  17711. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17712. if (cameraIndex > 0) {
  17713. this._engine.clear(null, false, true, true);
  17714. }
  17715. this._processSubCameras(this.activeCameras[cameraIndex]);
  17716. }
  17717. }
  17718. else {
  17719. if (!this.activeCamera) {
  17720. throw new Error("No camera defined");
  17721. }
  17722. this._processSubCameras(this.activeCamera);
  17723. }
  17724. // Intersection checks
  17725. this._checkIntersections();
  17726. // Update the audio listener attached to the camera
  17727. if (BABYLON.AudioEngine) {
  17728. this._updateAudioParameters();
  17729. }
  17730. // After render
  17731. if (this.afterRender) {
  17732. this.afterRender();
  17733. }
  17734. this.onAfterRenderObservable.notifyObservers(this);
  17735. // Cleaning
  17736. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17737. this._toBeDisposed.data[index].dispose();
  17738. this._toBeDisposed[index] = null;
  17739. }
  17740. this._toBeDisposed.reset();
  17741. if (this.dumpNextRenderTargets) {
  17742. this.dumpNextRenderTargets = false;
  17743. }
  17744. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17745. this._lastFrameDuration.endMonitoring();
  17746. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17747. this._totalLightsCounter.addCount(this.lights.length, true);
  17748. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17749. this._totalTexturesCounter.addCount(this.textures.length, true);
  17750. this._activeBones.addCount(0, true);
  17751. this._activeIndices.addCount(0, true);
  17752. this._activeParticles.addCount(0, true);
  17753. };
  17754. Scene.prototype._updateAudioParameters = function () {
  17755. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17756. return;
  17757. }
  17758. var listeningCamera;
  17759. var audioEngine = BABYLON.Engine.audioEngine;
  17760. if (this.activeCameras.length > 0) {
  17761. listeningCamera = this.activeCameras[0];
  17762. }
  17763. else {
  17764. listeningCamera = this.activeCamera;
  17765. }
  17766. if (listeningCamera && audioEngine.canUseWebAudio) {
  17767. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17768. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17769. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17770. cameraDirection.normalize();
  17771. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17772. var i;
  17773. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17774. var sound = this.mainSoundTrack.soundCollection[i];
  17775. if (sound.useCustomAttenuation) {
  17776. sound.updateDistanceFromListener();
  17777. }
  17778. }
  17779. for (i = 0; i < this.soundTracks.length; i++) {
  17780. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17781. sound = this.soundTracks[i].soundCollection[j];
  17782. if (sound.useCustomAttenuation) {
  17783. sound.updateDistanceFromListener();
  17784. }
  17785. }
  17786. }
  17787. }
  17788. };
  17789. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17790. // Audio
  17791. get: function () {
  17792. return this._audioEnabled;
  17793. },
  17794. set: function (value) {
  17795. this._audioEnabled = value;
  17796. if (BABYLON.AudioEngine) {
  17797. if (this._audioEnabled) {
  17798. this._enableAudio();
  17799. }
  17800. else {
  17801. this._disableAudio();
  17802. }
  17803. }
  17804. },
  17805. enumerable: true,
  17806. configurable: true
  17807. });
  17808. Scene.prototype._disableAudio = function () {
  17809. var i;
  17810. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17811. this.mainSoundTrack.soundCollection[i].pause();
  17812. }
  17813. for (i = 0; i < this.soundTracks.length; i++) {
  17814. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17815. this.soundTracks[i].soundCollection[j].pause();
  17816. }
  17817. }
  17818. };
  17819. Scene.prototype._enableAudio = function () {
  17820. var i;
  17821. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17822. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17823. this.mainSoundTrack.soundCollection[i].play();
  17824. }
  17825. }
  17826. for (i = 0; i < this.soundTracks.length; i++) {
  17827. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17828. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17829. this.soundTracks[i].soundCollection[j].play();
  17830. }
  17831. }
  17832. }
  17833. };
  17834. Object.defineProperty(Scene.prototype, "headphone", {
  17835. get: function () {
  17836. return this._headphone;
  17837. },
  17838. set: function (value) {
  17839. this._headphone = value;
  17840. if (BABYLON.AudioEngine) {
  17841. if (this._headphone) {
  17842. this._switchAudioModeForHeadphones();
  17843. }
  17844. else {
  17845. this._switchAudioModeForNormalSpeakers();
  17846. }
  17847. }
  17848. },
  17849. enumerable: true,
  17850. configurable: true
  17851. });
  17852. Scene.prototype._switchAudioModeForHeadphones = function () {
  17853. this.mainSoundTrack.switchPanningModelToHRTF();
  17854. for (var i = 0; i < this.soundTracks.length; i++) {
  17855. this.soundTracks[i].switchPanningModelToHRTF();
  17856. }
  17857. };
  17858. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17859. this.mainSoundTrack.switchPanningModelToEqualPower();
  17860. for (var i = 0; i < this.soundTracks.length; i++) {
  17861. this.soundTracks[i].switchPanningModelToEqualPower();
  17862. }
  17863. };
  17864. Scene.prototype.enableDepthRenderer = function () {
  17865. if (this._depthRenderer) {
  17866. return this._depthRenderer;
  17867. }
  17868. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17869. return this._depthRenderer;
  17870. };
  17871. Scene.prototype.disableDepthRenderer = function () {
  17872. if (!this._depthRenderer) {
  17873. return;
  17874. }
  17875. this._depthRenderer.dispose();
  17876. this._depthRenderer = null;
  17877. };
  17878. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17879. if (ratio === void 0) { ratio = 1; }
  17880. if (this._geometryBufferRenderer) {
  17881. return this._geometryBufferRenderer;
  17882. }
  17883. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  17884. if (!this._geometryBufferRenderer.isSupported) {
  17885. this._geometryBufferRenderer = null;
  17886. }
  17887. return this._geometryBufferRenderer;
  17888. };
  17889. Scene.prototype.disableGeometryBufferRenderer = function () {
  17890. if (!this._geometryBufferRenderer) {
  17891. return;
  17892. }
  17893. this._geometryBufferRenderer.dispose();
  17894. this._geometryBufferRenderer = null;
  17895. };
  17896. Scene.prototype.freezeMaterials = function () {
  17897. for (var i = 0; i < this.materials.length; i++) {
  17898. this.materials[i].freeze();
  17899. }
  17900. };
  17901. Scene.prototype.unfreezeMaterials = function () {
  17902. for (var i = 0; i < this.materials.length; i++) {
  17903. this.materials[i].unfreeze();
  17904. }
  17905. };
  17906. Scene.prototype.dispose = function () {
  17907. this.beforeRender = null;
  17908. this.afterRender = null;
  17909. this.skeletons = [];
  17910. this.morphTargetManagers = [];
  17911. this.importedMeshesFiles = new Array();
  17912. if (this._depthRenderer) {
  17913. this._depthRenderer.dispose();
  17914. }
  17915. // Smart arrays
  17916. if (this.activeCamera) {
  17917. this.activeCamera._activeMeshes.dispose();
  17918. this.activeCamera = null;
  17919. }
  17920. this._activeMeshes.dispose();
  17921. this._renderingManager.dispose();
  17922. this._processedMaterials.dispose();
  17923. this._activeParticleSystems.dispose();
  17924. this._activeSkeletons.dispose();
  17925. this._softwareSkinnedMeshes.dispose();
  17926. if (this._boundingBoxRenderer) {
  17927. this._boundingBoxRenderer.dispose();
  17928. }
  17929. this._meshesForIntersections.dispose();
  17930. this._toBeDisposed.dispose();
  17931. // Debug layer
  17932. if (this._debugLayer) {
  17933. this._debugLayer.hide();
  17934. }
  17935. // Events
  17936. this.onDisposeObservable.notifyObservers(this);
  17937. this.onDisposeObservable.clear();
  17938. this.onBeforeRenderObservable.clear();
  17939. this.onAfterRenderObservable.clear();
  17940. this.detachControl();
  17941. // Release sounds & sounds tracks
  17942. if (BABYLON.AudioEngine) {
  17943. this.disposeSounds();
  17944. }
  17945. // Detach cameras
  17946. var canvas = this._engine.getRenderingCanvas();
  17947. var index;
  17948. for (index = 0; index < this.cameras.length; index++) {
  17949. this.cameras[index].detachControl(canvas);
  17950. }
  17951. // Release lights
  17952. while (this.lights.length) {
  17953. this.lights[0].dispose();
  17954. }
  17955. // Release meshes
  17956. while (this.meshes.length) {
  17957. this.meshes[0].dispose(true);
  17958. }
  17959. // Release cameras
  17960. while (this.cameras.length) {
  17961. this.cameras[0].dispose();
  17962. }
  17963. // Release materials
  17964. while (this.materials.length) {
  17965. this.materials[0].dispose();
  17966. }
  17967. // Release particles
  17968. while (this.particleSystems.length) {
  17969. this.particleSystems[0].dispose();
  17970. }
  17971. // Release sprites
  17972. while (this.spriteManagers.length) {
  17973. this.spriteManagers[0].dispose();
  17974. }
  17975. // Release layers
  17976. while (this.layers.length) {
  17977. this.layers[0].dispose();
  17978. }
  17979. while (this.highlightLayers.length) {
  17980. this.highlightLayers[0].dispose();
  17981. }
  17982. // Release textures
  17983. while (this.textures.length) {
  17984. this.textures[0].dispose();
  17985. }
  17986. // Release UBO
  17987. this._sceneUbo.dispose();
  17988. // Post-processes
  17989. this.postProcessManager.dispose();
  17990. // Physics
  17991. if (this._physicsEngine) {
  17992. this.disablePhysicsEngine();
  17993. }
  17994. // Remove from engine
  17995. index = this._engine.scenes.indexOf(this);
  17996. if (index > -1) {
  17997. this._engine.scenes.splice(index, 1);
  17998. }
  17999. this._engine.wipeCaches();
  18000. this._engine = null;
  18001. };
  18002. Object.defineProperty(Scene.prototype, "isDisposed", {
  18003. get: function () {
  18004. return !this._engine;
  18005. },
  18006. enumerable: true,
  18007. configurable: true
  18008. });
  18009. // Release sounds & sounds tracks
  18010. Scene.prototype.disposeSounds = function () {
  18011. this.mainSoundTrack.dispose();
  18012. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18013. this.soundTracks[scIndex].dispose();
  18014. }
  18015. };
  18016. // Octrees
  18017. Scene.prototype.getWorldExtends = function () {
  18018. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18019. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18020. for (var index = 0; index < this.meshes.length; index++) {
  18021. var mesh = this.meshes[index];
  18022. mesh.computeWorldMatrix(true);
  18023. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18024. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18025. BABYLON.Tools.CheckExtends(minBox, min, max);
  18026. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18027. }
  18028. return {
  18029. min: min,
  18030. max: max
  18031. };
  18032. };
  18033. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18034. if (maxCapacity === void 0) { maxCapacity = 64; }
  18035. if (maxDepth === void 0) { maxDepth = 2; }
  18036. if (!this._selectionOctree) {
  18037. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18038. }
  18039. var worldExtends = this.getWorldExtends();
  18040. // Update octree
  18041. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18042. return this._selectionOctree;
  18043. };
  18044. // Picking
  18045. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18046. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18047. var engine = this._engine;
  18048. if (!camera) {
  18049. if (!this.activeCamera)
  18050. throw new Error("Active camera not set");
  18051. camera = this.activeCamera;
  18052. }
  18053. var cameraViewport = camera.viewport;
  18054. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18055. // Moving coordinates to local viewport world
  18056. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18057. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18058. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18059. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18060. };
  18061. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18062. if (!BABYLON.PickingInfo) {
  18063. return null;
  18064. }
  18065. var engine = this._engine;
  18066. if (!camera) {
  18067. if (!this.activeCamera)
  18068. throw new Error("Active camera not set");
  18069. camera = this.activeCamera;
  18070. }
  18071. var cameraViewport = camera.viewport;
  18072. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18073. var identity = BABYLON.Matrix.Identity();
  18074. // Moving coordinates to local viewport world
  18075. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18076. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18077. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18078. };
  18079. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18080. if (!BABYLON.PickingInfo) {
  18081. return null;
  18082. }
  18083. var pickingInfo = null;
  18084. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18085. var mesh = this.meshes[meshIndex];
  18086. if (predicate) {
  18087. if (!predicate(mesh)) {
  18088. continue;
  18089. }
  18090. }
  18091. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18092. continue;
  18093. }
  18094. var world = mesh.getWorldMatrix();
  18095. var ray = rayFunction(world);
  18096. var result = mesh.intersects(ray, fastCheck);
  18097. if (!result || !result.hit)
  18098. continue;
  18099. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18100. continue;
  18101. pickingInfo = result;
  18102. if (fastCheck) {
  18103. break;
  18104. }
  18105. }
  18106. return pickingInfo || new BABYLON.PickingInfo();
  18107. };
  18108. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18109. if (!BABYLON.PickingInfo) {
  18110. return null;
  18111. }
  18112. var pickingInfos = new Array();
  18113. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18114. var mesh = this.meshes[meshIndex];
  18115. if (predicate) {
  18116. if (!predicate(mesh)) {
  18117. continue;
  18118. }
  18119. }
  18120. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18121. continue;
  18122. }
  18123. var world = mesh.getWorldMatrix();
  18124. var ray = rayFunction(world);
  18125. var result = mesh.intersects(ray, false);
  18126. if (!result || !result.hit)
  18127. continue;
  18128. pickingInfos.push(result);
  18129. }
  18130. return pickingInfos;
  18131. };
  18132. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18133. if (!BABYLON.PickingInfo) {
  18134. return null;
  18135. }
  18136. var pickingInfo = null;
  18137. camera = camera || this.activeCamera;
  18138. if (this.spriteManagers.length > 0) {
  18139. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18140. var spriteManager = this.spriteManagers[spriteIndex];
  18141. if (!spriteManager.isPickable) {
  18142. continue;
  18143. }
  18144. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18145. if (!result || !result.hit)
  18146. continue;
  18147. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18148. continue;
  18149. pickingInfo = result;
  18150. if (fastCheck) {
  18151. break;
  18152. }
  18153. }
  18154. }
  18155. return pickingInfo || new BABYLON.PickingInfo();
  18156. };
  18157. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18158. /// <param name="x">X position on screen</param>
  18159. /// <param name="y">Y position on screen</param>
  18160. /// <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>
  18161. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18162. /// <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>
  18163. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18164. var _this = this;
  18165. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18166. };
  18167. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18168. /// <param name="x">X position on screen</param>
  18169. /// <param name="y">Y position on screen</param>
  18170. /// <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>
  18171. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18172. /// <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>
  18173. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18174. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18175. };
  18176. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18177. var _this = this;
  18178. return this._internalPick(function (world) {
  18179. if (!_this._pickWithRayInverseMatrix) {
  18180. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18181. }
  18182. world.invertToRef(_this._pickWithRayInverseMatrix);
  18183. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18184. }, predicate, fastCheck);
  18185. };
  18186. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18187. /// <param name="x">X position on screen</param>
  18188. /// <param name="y">Y position on screen</param>
  18189. /// <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>
  18190. /// <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>
  18191. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18192. var _this = this;
  18193. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18194. };
  18195. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18196. /// <param name="ray">Ray to use</param>
  18197. /// <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>
  18198. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18199. var _this = this;
  18200. return this._internalMultiPick(function (world) {
  18201. if (!_this._pickWithRayInverseMatrix) {
  18202. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18203. }
  18204. world.invertToRef(_this._pickWithRayInverseMatrix);
  18205. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18206. }, predicate);
  18207. };
  18208. Scene.prototype.setPointerOverMesh = function (mesh) {
  18209. if (this._pointerOverMesh === mesh) {
  18210. return;
  18211. }
  18212. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18213. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18214. }
  18215. this._pointerOverMesh = mesh;
  18216. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18217. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18218. }
  18219. };
  18220. Scene.prototype.getPointerOverMesh = function () {
  18221. return this._pointerOverMesh;
  18222. };
  18223. Scene.prototype.setPointerOverSprite = function (sprite) {
  18224. if (this._pointerOverSprite === sprite) {
  18225. return;
  18226. }
  18227. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18228. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18229. }
  18230. this._pointerOverSprite = sprite;
  18231. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18232. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18233. }
  18234. };
  18235. Scene.prototype.getPointerOverSprite = function () {
  18236. return this._pointerOverSprite;
  18237. };
  18238. // Physics
  18239. Scene.prototype.getPhysicsEngine = function () {
  18240. return this._physicsEngine;
  18241. };
  18242. /**
  18243. * Enables physics to the current scene
  18244. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18245. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18246. * @return {boolean} was the physics engine initialized
  18247. */
  18248. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18249. if (this._physicsEngine) {
  18250. return true;
  18251. }
  18252. try {
  18253. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18254. return true;
  18255. }
  18256. catch (e) {
  18257. BABYLON.Tools.Error(e.message);
  18258. return false;
  18259. }
  18260. };
  18261. Scene.prototype.disablePhysicsEngine = function () {
  18262. if (!this._physicsEngine) {
  18263. return;
  18264. }
  18265. this._physicsEngine.dispose();
  18266. this._physicsEngine = undefined;
  18267. };
  18268. Scene.prototype.isPhysicsEnabled = function () {
  18269. return this._physicsEngine !== undefined;
  18270. };
  18271. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18272. var mesh = compound.parts[0].mesh;
  18273. mesh.physicsImpostor.dispose();
  18274. mesh.physicsImpostor = null;
  18275. };
  18276. // Misc.
  18277. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18278. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18279. // Light
  18280. if (this.lights.length === 0) {
  18281. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18282. }
  18283. // Camera
  18284. if (!this.activeCamera) {
  18285. var worldExtends = this.getWorldExtends();
  18286. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18287. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18288. var camera;
  18289. var radius = worldSize.length() * 1.5;
  18290. if (createArcRotateCamera) {
  18291. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18292. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18293. arcRotateCamera.wheelPrecision = 100 / radius;
  18294. camera = arcRotateCamera;
  18295. }
  18296. else {
  18297. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18298. freeCamera.setTarget(worldCenter);
  18299. camera = freeCamera;
  18300. }
  18301. camera.minZ = radius * 0.01;
  18302. camera.maxZ = radius * 100;
  18303. camera.speed = radius * 0.2;
  18304. this.activeCamera = camera;
  18305. }
  18306. };
  18307. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18308. if (pbr === void 0) { pbr = false; }
  18309. if (environmentTexture) {
  18310. this.environmentTexture = environmentTexture;
  18311. }
  18312. if (!this.environmentTexture) {
  18313. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18314. return;
  18315. }
  18316. if (!this.environmentTexture) {
  18317. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18318. return;
  18319. }
  18320. // Skybox
  18321. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18322. if (pbr) {
  18323. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18324. hdrSkyboxMaterial.backFaceCulling = false;
  18325. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18326. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18327. hdrSkyboxMaterial.microSurface = 1.0;
  18328. hdrSkyboxMaterial.disableLighting = true;
  18329. hdrSkybox.infiniteDistance = true;
  18330. hdrSkybox.material = hdrSkyboxMaterial;
  18331. }
  18332. else {
  18333. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18334. skyboxMaterial.backFaceCulling = false;
  18335. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18336. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18337. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18338. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18339. skyboxMaterial.disableLighting = true;
  18340. hdrSkybox.infiniteDistance = true;
  18341. hdrSkybox.material = skyboxMaterial;
  18342. }
  18343. return hdrSkybox;
  18344. };
  18345. // Tags
  18346. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18347. if (tagsQuery === undefined) {
  18348. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18349. return list;
  18350. }
  18351. var listByTags = [];
  18352. forEach = forEach || (function (item) { return; });
  18353. for (var i in list) {
  18354. var item = list[i];
  18355. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18356. listByTags.push(item);
  18357. forEach(item);
  18358. }
  18359. }
  18360. return listByTags;
  18361. };
  18362. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18363. return this._getByTags(this.meshes, tagsQuery, forEach);
  18364. };
  18365. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18366. return this._getByTags(this.cameras, tagsQuery, forEach);
  18367. };
  18368. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18369. return this._getByTags(this.lights, tagsQuery, forEach);
  18370. };
  18371. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18372. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18373. };
  18374. /**
  18375. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18376. * This allowed control for front to back rendering or reversly depending of the special needs.
  18377. *
  18378. * @param renderingGroupId The rendering group id corresponding to its index
  18379. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18380. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18381. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18382. */
  18383. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18384. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18385. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18386. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18387. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18388. };
  18389. /**
  18390. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18391. *
  18392. * @param renderingGroupId The rendering group id corresponding to its index
  18393. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18394. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18395. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18396. */
  18397. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18398. if (depth === void 0) { depth = true; }
  18399. if (stencil === void 0) { stencil = true; }
  18400. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18401. };
  18402. /**
  18403. * Will flag all materials as dirty to trigger new shader compilation
  18404. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18405. */
  18406. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18407. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18408. var material = _a[_i];
  18409. if (predicate && !predicate(material)) {
  18410. continue;
  18411. }
  18412. material.markAsDirty(flag);
  18413. }
  18414. };
  18415. return Scene;
  18416. }());
  18417. // Statics
  18418. Scene._FOGMODE_NONE = 0;
  18419. Scene._FOGMODE_EXP = 1;
  18420. Scene._FOGMODE_EXP2 = 2;
  18421. Scene._FOGMODE_LINEAR = 3;
  18422. Scene.MinDeltaTime = 1.0;
  18423. Scene.MaxDeltaTime = 1000.0;
  18424. Scene.DragMovementThreshold = 10; // in pixels
  18425. Scene.LongPressDelay = 500; // in milliseconds
  18426. Scene.DoubleClickDelay = 300; // in milliseconds
  18427. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18428. BABYLON.Scene = Scene;
  18429. })(BABYLON || (BABYLON = {}));
  18430. //# sourceMappingURL=babylon.scene.js.map
  18431. var BABYLON;
  18432. (function (BABYLON) {
  18433. var Buffer = (function () {
  18434. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18435. if (engine instanceof BABYLON.Mesh) {
  18436. this._engine = engine.getScene().getEngine();
  18437. }
  18438. else {
  18439. this._engine = engine;
  18440. }
  18441. this._updatable = updatable;
  18442. this._data = data;
  18443. this._strideSize = stride;
  18444. if (!postponeInternalCreation) {
  18445. this.create();
  18446. }
  18447. this._instanced = instanced;
  18448. }
  18449. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18450. // a lot of these parameters are ignored as they are overriden by the buffer
  18451. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18452. };
  18453. // Properties
  18454. Buffer.prototype.isUpdatable = function () {
  18455. return this._updatable;
  18456. };
  18457. Buffer.prototype.getData = function () {
  18458. return this._data;
  18459. };
  18460. Buffer.prototype.getBuffer = function () {
  18461. return this._buffer;
  18462. };
  18463. Buffer.prototype.getStrideSize = function () {
  18464. return this._strideSize;
  18465. };
  18466. Buffer.prototype.getIsInstanced = function () {
  18467. return this._instanced;
  18468. };
  18469. // Methods
  18470. Buffer.prototype.create = function (data) {
  18471. if (!data && this._buffer) {
  18472. return; // nothing to do
  18473. }
  18474. data = data || this._data;
  18475. if (!this._buffer) {
  18476. if (this._updatable) {
  18477. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18478. this._data = data;
  18479. }
  18480. else {
  18481. this._buffer = this._engine.createVertexBuffer(data);
  18482. }
  18483. }
  18484. else if (this._updatable) {
  18485. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18486. this._data = data;
  18487. }
  18488. };
  18489. Buffer.prototype.update = function (data) {
  18490. this.create(data);
  18491. };
  18492. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18493. if (!this._buffer) {
  18494. return;
  18495. }
  18496. if (this._updatable) {
  18497. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18498. this._data = null;
  18499. }
  18500. };
  18501. Buffer.prototype.dispose = function () {
  18502. if (!this._buffer) {
  18503. return;
  18504. }
  18505. if (this._engine._releaseBuffer(this._buffer)) {
  18506. this._buffer = null;
  18507. }
  18508. };
  18509. return Buffer;
  18510. }());
  18511. BABYLON.Buffer = Buffer;
  18512. })(BABYLON || (BABYLON = {}));
  18513. //# sourceMappingURL=babylon.buffer.js.map
  18514. var BABYLON;
  18515. (function (BABYLON) {
  18516. var VertexBuffer = (function () {
  18517. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18518. if (!stride) {
  18519. // Deduce stride from kind
  18520. switch (kind) {
  18521. case VertexBuffer.PositionKind:
  18522. stride = 3;
  18523. break;
  18524. case VertexBuffer.NormalKind:
  18525. stride = 3;
  18526. break;
  18527. case VertexBuffer.UVKind:
  18528. case VertexBuffer.UV2Kind:
  18529. case VertexBuffer.UV3Kind:
  18530. case VertexBuffer.UV4Kind:
  18531. case VertexBuffer.UV5Kind:
  18532. case VertexBuffer.UV6Kind:
  18533. stride = 2;
  18534. break;
  18535. case VertexBuffer.TangentKind:
  18536. case VertexBuffer.ColorKind:
  18537. stride = 4;
  18538. break;
  18539. case VertexBuffer.MatricesIndicesKind:
  18540. case VertexBuffer.MatricesIndicesExtraKind:
  18541. stride = 4;
  18542. break;
  18543. case VertexBuffer.MatricesWeightsKind:
  18544. case VertexBuffer.MatricesWeightsExtraKind:
  18545. stride = 4;
  18546. break;
  18547. }
  18548. }
  18549. if (data instanceof BABYLON.Buffer) {
  18550. if (!stride) {
  18551. stride = data.getStrideSize();
  18552. }
  18553. this._buffer = data;
  18554. this._ownsBuffer = false;
  18555. }
  18556. else {
  18557. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18558. this._ownsBuffer = true;
  18559. }
  18560. this._stride = stride;
  18561. this._offset = offset ? offset : 0;
  18562. this._size = size ? size : stride;
  18563. this._kind = kind;
  18564. }
  18565. /**
  18566. * Returns the kind of the VertexBuffer (string).
  18567. */
  18568. VertexBuffer.prototype.getKind = function () {
  18569. return this._kind;
  18570. };
  18571. // Properties
  18572. /**
  18573. * Boolean : is the VertexBuffer updatable ?
  18574. */
  18575. VertexBuffer.prototype.isUpdatable = function () {
  18576. return this._buffer.isUpdatable();
  18577. };
  18578. /**
  18579. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18580. */
  18581. VertexBuffer.prototype.getData = function () {
  18582. return this._buffer.getData();
  18583. };
  18584. /**
  18585. * Returns the WebGLBuffer associated to the VertexBuffer.
  18586. */
  18587. VertexBuffer.prototype.getBuffer = function () {
  18588. return this._buffer.getBuffer();
  18589. };
  18590. /**
  18591. * Returns the stride of the VertexBuffer (integer).
  18592. */
  18593. VertexBuffer.prototype.getStrideSize = function () {
  18594. return this._stride;
  18595. };
  18596. /**
  18597. * Returns the offset (integer).
  18598. */
  18599. VertexBuffer.prototype.getOffset = function () {
  18600. return this._offset;
  18601. };
  18602. /**
  18603. * Returns the VertexBuffer total size (integer).
  18604. */
  18605. VertexBuffer.prototype.getSize = function () {
  18606. return this._size;
  18607. };
  18608. /**
  18609. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18610. */
  18611. VertexBuffer.prototype.getIsInstanced = function () {
  18612. return this._buffer.getIsInstanced();
  18613. };
  18614. // Methods
  18615. /**
  18616. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18617. * Returns the created WebGLBuffer.
  18618. */
  18619. VertexBuffer.prototype.create = function (data) {
  18620. return this._buffer.create(data);
  18621. };
  18622. /**
  18623. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18624. * Returns the updated WebGLBuffer.
  18625. */
  18626. VertexBuffer.prototype.update = function (data) {
  18627. return this._buffer.update(data);
  18628. };
  18629. /**
  18630. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18631. * Returns the directly updated WebGLBuffer.
  18632. */
  18633. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18634. return this._buffer.updateDirectly(data, offset);
  18635. };
  18636. /**
  18637. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18638. */
  18639. VertexBuffer.prototype.dispose = function () {
  18640. if (this._ownsBuffer) {
  18641. this._buffer.dispose();
  18642. }
  18643. };
  18644. Object.defineProperty(VertexBuffer, "PositionKind", {
  18645. get: function () {
  18646. return VertexBuffer._PositionKind;
  18647. },
  18648. enumerable: true,
  18649. configurable: true
  18650. });
  18651. Object.defineProperty(VertexBuffer, "NormalKind", {
  18652. get: function () {
  18653. return VertexBuffer._NormalKind;
  18654. },
  18655. enumerable: true,
  18656. configurable: true
  18657. });
  18658. Object.defineProperty(VertexBuffer, "TangentKind", {
  18659. get: function () {
  18660. return VertexBuffer._TangentKind;
  18661. },
  18662. enumerable: true,
  18663. configurable: true
  18664. });
  18665. Object.defineProperty(VertexBuffer, "UVKind", {
  18666. get: function () {
  18667. return VertexBuffer._UVKind;
  18668. },
  18669. enumerable: true,
  18670. configurable: true
  18671. });
  18672. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18673. get: function () {
  18674. return VertexBuffer._UV2Kind;
  18675. },
  18676. enumerable: true,
  18677. configurable: true
  18678. });
  18679. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18680. get: function () {
  18681. return VertexBuffer._UV3Kind;
  18682. },
  18683. enumerable: true,
  18684. configurable: true
  18685. });
  18686. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18687. get: function () {
  18688. return VertexBuffer._UV4Kind;
  18689. },
  18690. enumerable: true,
  18691. configurable: true
  18692. });
  18693. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18694. get: function () {
  18695. return VertexBuffer._UV5Kind;
  18696. },
  18697. enumerable: true,
  18698. configurable: true
  18699. });
  18700. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18701. get: function () {
  18702. return VertexBuffer._UV6Kind;
  18703. },
  18704. enumerable: true,
  18705. configurable: true
  18706. });
  18707. Object.defineProperty(VertexBuffer, "ColorKind", {
  18708. get: function () {
  18709. return VertexBuffer._ColorKind;
  18710. },
  18711. enumerable: true,
  18712. configurable: true
  18713. });
  18714. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18715. get: function () {
  18716. return VertexBuffer._MatricesIndicesKind;
  18717. },
  18718. enumerable: true,
  18719. configurable: true
  18720. });
  18721. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18722. get: function () {
  18723. return VertexBuffer._MatricesWeightsKind;
  18724. },
  18725. enumerable: true,
  18726. configurable: true
  18727. });
  18728. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18729. get: function () {
  18730. return VertexBuffer._MatricesIndicesExtraKind;
  18731. },
  18732. enumerable: true,
  18733. configurable: true
  18734. });
  18735. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18736. get: function () {
  18737. return VertexBuffer._MatricesWeightsExtraKind;
  18738. },
  18739. enumerable: true,
  18740. configurable: true
  18741. });
  18742. return VertexBuffer;
  18743. }());
  18744. // Enums
  18745. VertexBuffer._PositionKind = "position";
  18746. VertexBuffer._NormalKind = "normal";
  18747. VertexBuffer._TangentKind = "tangent";
  18748. VertexBuffer._UVKind = "uv";
  18749. VertexBuffer._UV2Kind = "uv2";
  18750. VertexBuffer._UV3Kind = "uv3";
  18751. VertexBuffer._UV4Kind = "uv4";
  18752. VertexBuffer._UV5Kind = "uv5";
  18753. VertexBuffer._UV6Kind = "uv6";
  18754. VertexBuffer._ColorKind = "color";
  18755. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18756. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18757. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18758. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18759. BABYLON.VertexBuffer = VertexBuffer;
  18760. })(BABYLON || (BABYLON = {}));
  18761. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18762. var BABYLON;
  18763. (function (BABYLON) {
  18764. var BaseTexture = (function () {
  18765. function BaseTexture(scene) {
  18766. this._hasAlpha = false;
  18767. this.getAlphaFromRGB = false;
  18768. this.level = 1;
  18769. this.coordinatesIndex = 0;
  18770. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18771. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18772. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18773. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18774. this.isCube = false;
  18775. this.isRenderTarget = false;
  18776. this.animations = new Array();
  18777. /**
  18778. * An event triggered when the texture is disposed.
  18779. * @type {BABYLON.Observable}
  18780. */
  18781. this.onDisposeObservable = new BABYLON.Observable();
  18782. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18783. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18784. this._scene.textures.push(this);
  18785. this._uid = null;
  18786. }
  18787. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18788. get: function () {
  18789. return this._hasAlpha;
  18790. },
  18791. set: function (value) {
  18792. if (this._hasAlpha === value) {
  18793. return;
  18794. }
  18795. this._hasAlpha = value;
  18796. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18797. },
  18798. enumerable: true,
  18799. configurable: true
  18800. });
  18801. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18802. get: function () {
  18803. return this._coordinatesMode;
  18804. },
  18805. set: function (value) {
  18806. if (this._coordinatesMode === value) {
  18807. return;
  18808. }
  18809. this._coordinatesMode = value;
  18810. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18811. },
  18812. enumerable: true,
  18813. configurable: true
  18814. });
  18815. Object.defineProperty(BaseTexture.prototype, "uid", {
  18816. get: function () {
  18817. if (!this._uid) {
  18818. this._uid = BABYLON.Tools.RandomId();
  18819. }
  18820. return this._uid;
  18821. },
  18822. enumerable: true,
  18823. configurable: true
  18824. });
  18825. BaseTexture.prototype.toString = function () {
  18826. return this.name;
  18827. };
  18828. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18829. set: function (callback) {
  18830. if (this._onDisposeObserver) {
  18831. this.onDisposeObservable.remove(this._onDisposeObserver);
  18832. }
  18833. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18834. },
  18835. enumerable: true,
  18836. configurable: true
  18837. });
  18838. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18839. get: function () {
  18840. return true;
  18841. },
  18842. enumerable: true,
  18843. configurable: true
  18844. });
  18845. BaseTexture.prototype.getScene = function () {
  18846. return this._scene;
  18847. };
  18848. BaseTexture.prototype.getTextureMatrix = function () {
  18849. return null;
  18850. };
  18851. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18852. return null;
  18853. };
  18854. BaseTexture.prototype.getInternalTexture = function () {
  18855. return this._texture;
  18856. };
  18857. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18858. return !this.isBlocking || this.isReady();
  18859. };
  18860. BaseTexture.prototype.isReady = function () {
  18861. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18862. this.delayLoad();
  18863. return false;
  18864. }
  18865. if (this._texture) {
  18866. return this._texture.isReady;
  18867. }
  18868. return false;
  18869. };
  18870. BaseTexture.prototype.getSize = function () {
  18871. if (this._texture._width) {
  18872. return new BABYLON.Size(this._texture._width, this._texture._height);
  18873. }
  18874. if (this._texture._size) {
  18875. return new BABYLON.Size(this._texture._size, this._texture._size);
  18876. }
  18877. return BABYLON.Size.Zero();
  18878. };
  18879. BaseTexture.prototype.getBaseSize = function () {
  18880. if (!this.isReady() || !this._texture)
  18881. return BABYLON.Size.Zero();
  18882. if (this._texture._size) {
  18883. return new BABYLON.Size(this._texture._size, this._texture._size);
  18884. }
  18885. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  18886. };
  18887. BaseTexture.prototype.scale = function (ratio) {
  18888. };
  18889. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18890. get: function () {
  18891. return false;
  18892. },
  18893. enumerable: true,
  18894. configurable: true
  18895. });
  18896. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18897. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18898. for (var index = 0; index < texturesCache.length; index++) {
  18899. var texturesCacheEntry = texturesCache[index];
  18900. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18901. texturesCache.splice(index, 1);
  18902. return;
  18903. }
  18904. }
  18905. };
  18906. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18907. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18908. for (var index = 0; index < texturesCache.length; index++) {
  18909. var texturesCacheEntry = texturesCache[index];
  18910. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18911. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18912. texturesCacheEntry.references++;
  18913. return texturesCacheEntry;
  18914. }
  18915. }
  18916. }
  18917. return null;
  18918. };
  18919. BaseTexture.prototype.delayLoad = function () {
  18920. };
  18921. BaseTexture.prototype.clone = function () {
  18922. return null;
  18923. };
  18924. BaseTexture.prototype.releaseInternalTexture = function () {
  18925. if (this._texture) {
  18926. this._scene.getEngine().releaseInternalTexture(this._texture);
  18927. delete this._texture;
  18928. }
  18929. };
  18930. BaseTexture.prototype.dispose = function () {
  18931. // Animations
  18932. this.getScene().stopAnimation(this);
  18933. // Remove from scene
  18934. this._scene._removePendingData(this);
  18935. var index = this._scene.textures.indexOf(this);
  18936. if (index >= 0) {
  18937. this._scene.textures.splice(index, 1);
  18938. }
  18939. if (this._texture === undefined) {
  18940. return;
  18941. }
  18942. // Release
  18943. this.releaseInternalTexture();
  18944. // Callback
  18945. this.onDisposeObservable.notifyObservers(this);
  18946. this.onDisposeObservable.clear();
  18947. };
  18948. BaseTexture.prototype.serialize = function () {
  18949. if (!this.name) {
  18950. return null;
  18951. }
  18952. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18953. // Animations
  18954. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18955. return serializationObject;
  18956. };
  18957. return BaseTexture;
  18958. }());
  18959. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  18960. __decorate([
  18961. BABYLON.serialize()
  18962. ], BaseTexture.prototype, "name", void 0);
  18963. __decorate([
  18964. BABYLON.serialize("hasAlpha")
  18965. ], BaseTexture.prototype, "_hasAlpha", void 0);
  18966. __decorate([
  18967. BABYLON.serialize()
  18968. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  18969. __decorate([
  18970. BABYLON.serialize()
  18971. ], BaseTexture.prototype, "level", void 0);
  18972. __decorate([
  18973. BABYLON.serialize()
  18974. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18975. __decorate([
  18976. BABYLON.serialize("coordinatesMode")
  18977. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  18978. __decorate([
  18979. BABYLON.serialize()
  18980. ], BaseTexture.prototype, "wrapU", void 0);
  18981. __decorate([
  18982. BABYLON.serialize()
  18983. ], BaseTexture.prototype, "wrapV", void 0);
  18984. __decorate([
  18985. BABYLON.serialize()
  18986. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  18987. __decorate([
  18988. BABYLON.serialize()
  18989. ], BaseTexture.prototype, "isCube", void 0);
  18990. __decorate([
  18991. BABYLON.serialize()
  18992. ], BaseTexture.prototype, "isRenderTarget", void 0);
  18993. BABYLON.BaseTexture = BaseTexture;
  18994. })(BABYLON || (BABYLON = {}));
  18995. //# sourceMappingURL=babylon.baseTexture.js.map
  18996. var BABYLON;
  18997. (function (BABYLON) {
  18998. var Texture = (function (_super) {
  18999. __extends(Texture, _super);
  19000. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19001. if (noMipmap === void 0) { noMipmap = false; }
  19002. if (invertY === void 0) { invertY = true; }
  19003. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19004. if (onLoad === void 0) { onLoad = null; }
  19005. if (onError === void 0) { onError = null; }
  19006. if (buffer === void 0) { buffer = null; }
  19007. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19008. var _this = _super.call(this, scene) || this;
  19009. _this.uOffset = 0;
  19010. _this.vOffset = 0;
  19011. _this.uScale = 1.0;
  19012. _this.vScale = 1.0;
  19013. _this.uAng = 0;
  19014. _this.vAng = 0;
  19015. _this.wAng = 0;
  19016. _this._isBlocking = true;
  19017. _this.name = url;
  19018. _this.url = url;
  19019. _this._noMipmap = noMipmap;
  19020. _this._invertY = invertY;
  19021. _this._samplingMode = samplingMode;
  19022. _this._buffer = buffer;
  19023. _this._deleteBuffer = deleteBuffer;
  19024. _this._format = format;
  19025. scene = _this.getScene();
  19026. if (!url) {
  19027. return _this;
  19028. }
  19029. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19030. var load = function () {
  19031. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  19032. _this.onLoadObservable.notifyObservers(true);
  19033. }
  19034. if (onLoad) {
  19035. onLoad();
  19036. }
  19037. if (!_this.isBlocking) {
  19038. scene.resetCachedMaterial();
  19039. }
  19040. };
  19041. if (!_this._texture) {
  19042. if (!scene.useDelayedTextureLoading) {
  19043. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19044. if (deleteBuffer) {
  19045. delete _this._buffer;
  19046. }
  19047. }
  19048. else {
  19049. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19050. _this._delayedOnLoad = load;
  19051. _this._delayedOnError = onError;
  19052. }
  19053. }
  19054. else {
  19055. if (_this._texture.isReady) {
  19056. BABYLON.Tools.SetImmediate(function () { return load(); });
  19057. }
  19058. else {
  19059. _this._texture.onLoadedCallbacks.push(load);
  19060. }
  19061. }
  19062. return _this;
  19063. }
  19064. Object.defineProperty(Texture.prototype, "noMipmap", {
  19065. get: function () {
  19066. return this._noMipmap;
  19067. },
  19068. enumerable: true,
  19069. configurable: true
  19070. });
  19071. Object.defineProperty(Texture.prototype, "isBlocking", {
  19072. get: function () {
  19073. return this._isBlocking;
  19074. },
  19075. set: function (value) {
  19076. this._isBlocking = value;
  19077. },
  19078. enumerable: true,
  19079. configurable: true
  19080. });
  19081. Texture.prototype.delayLoad = function () {
  19082. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19083. return;
  19084. }
  19085. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19086. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19087. if (!this._texture) {
  19088. 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);
  19089. if (this._deleteBuffer) {
  19090. delete this._buffer;
  19091. }
  19092. }
  19093. };
  19094. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19095. if (!this._texture) {
  19096. return;
  19097. }
  19098. this._samplingMode = samplingMode;
  19099. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19100. };
  19101. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19102. x *= this.uScale;
  19103. y *= this.vScale;
  19104. x -= 0.5 * this.uScale;
  19105. y -= 0.5 * this.vScale;
  19106. z -= 0.5;
  19107. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19108. t.x += 0.5 * this.uScale + this.uOffset;
  19109. t.y += 0.5 * this.vScale + this.vOffset;
  19110. t.z += 0.5;
  19111. };
  19112. Texture.prototype.getTextureMatrix = function () {
  19113. if (this.uOffset === this._cachedUOffset &&
  19114. this.vOffset === this._cachedVOffset &&
  19115. this.uScale === this._cachedUScale &&
  19116. this.vScale === this._cachedVScale &&
  19117. this.uAng === this._cachedUAng &&
  19118. this.vAng === this._cachedVAng &&
  19119. this.wAng === this._cachedWAng) {
  19120. return this._cachedTextureMatrix;
  19121. }
  19122. this._cachedUOffset = this.uOffset;
  19123. this._cachedVOffset = this.vOffset;
  19124. this._cachedUScale = this.uScale;
  19125. this._cachedVScale = this.vScale;
  19126. this._cachedUAng = this.uAng;
  19127. this._cachedVAng = this.vAng;
  19128. this._cachedWAng = this.wAng;
  19129. if (!this._cachedTextureMatrix) {
  19130. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19131. this._rowGenerationMatrix = new BABYLON.Matrix();
  19132. this._t0 = BABYLON.Vector3.Zero();
  19133. this._t1 = BABYLON.Vector3.Zero();
  19134. this._t2 = BABYLON.Vector3.Zero();
  19135. }
  19136. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19137. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19138. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19139. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19140. this._t1.subtractInPlace(this._t0);
  19141. this._t2.subtractInPlace(this._t0);
  19142. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19143. this._cachedTextureMatrix.m[0] = this._t1.x;
  19144. this._cachedTextureMatrix.m[1] = this._t1.y;
  19145. this._cachedTextureMatrix.m[2] = this._t1.z;
  19146. this._cachedTextureMatrix.m[4] = this._t2.x;
  19147. this._cachedTextureMatrix.m[5] = this._t2.y;
  19148. this._cachedTextureMatrix.m[6] = this._t2.z;
  19149. this._cachedTextureMatrix.m[8] = this._t0.x;
  19150. this._cachedTextureMatrix.m[9] = this._t0.y;
  19151. this._cachedTextureMatrix.m[10] = this._t0.z;
  19152. return this._cachedTextureMatrix;
  19153. };
  19154. Texture.prototype.getReflectionTextureMatrix = function () {
  19155. if (this.uOffset === this._cachedUOffset &&
  19156. this.vOffset === this._cachedVOffset &&
  19157. this.uScale === this._cachedUScale &&
  19158. this.vScale === this._cachedVScale &&
  19159. this.coordinatesMode === this._cachedCoordinatesMode) {
  19160. return this._cachedTextureMatrix;
  19161. }
  19162. if (!this._cachedTextureMatrix) {
  19163. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19164. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19165. }
  19166. this._cachedCoordinatesMode = this.coordinatesMode;
  19167. switch (this.coordinatesMode) {
  19168. case Texture.PLANAR_MODE:
  19169. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19170. this._cachedTextureMatrix[0] = this.uScale;
  19171. this._cachedTextureMatrix[5] = this.vScale;
  19172. this._cachedTextureMatrix[12] = this.uOffset;
  19173. this._cachedTextureMatrix[13] = this.vOffset;
  19174. break;
  19175. case Texture.PROJECTION_MODE:
  19176. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19177. this._projectionModeMatrix.m[0] = 0.5;
  19178. this._projectionModeMatrix.m[5] = -0.5;
  19179. this._projectionModeMatrix.m[10] = 0.0;
  19180. this._projectionModeMatrix.m[12] = 0.5;
  19181. this._projectionModeMatrix.m[13] = 0.5;
  19182. this._projectionModeMatrix.m[14] = 1.0;
  19183. this._projectionModeMatrix.m[15] = 1.0;
  19184. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19185. break;
  19186. default:
  19187. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19188. break;
  19189. }
  19190. return this._cachedTextureMatrix;
  19191. };
  19192. Texture.prototype.clone = function () {
  19193. var _this = this;
  19194. return BABYLON.SerializationHelper.Clone(function () {
  19195. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19196. }, this);
  19197. };
  19198. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19199. get: function () {
  19200. if (!this._onLoadObservarble) {
  19201. this._onLoadObservarble = new BABYLON.Observable();
  19202. }
  19203. return this._onLoadObservarble;
  19204. },
  19205. enumerable: true,
  19206. configurable: true
  19207. });
  19208. // Statics
  19209. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19210. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19211. if (onLoad === void 0) { onLoad = null; }
  19212. if (onError === void 0) { onError = null; }
  19213. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19214. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19215. };
  19216. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19217. if (parsedTexture.customType) {
  19218. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19219. // Update Sampling Mode
  19220. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19221. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19222. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19223. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19224. }
  19225. }
  19226. return parsedCustomTexture;
  19227. }
  19228. if (parsedTexture.isCube) {
  19229. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19230. }
  19231. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19232. return null;
  19233. }
  19234. var texture = BABYLON.SerializationHelper.Parse(function () {
  19235. if (parsedTexture.mirrorPlane) {
  19236. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19237. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19238. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19239. return mirrorTexture;
  19240. }
  19241. else if (parsedTexture.isRenderTarget) {
  19242. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19243. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19244. return renderTargetTexture;
  19245. }
  19246. else {
  19247. var texture;
  19248. if (parsedTexture.base64String) {
  19249. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19250. }
  19251. else {
  19252. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19253. }
  19254. return texture;
  19255. }
  19256. }, parsedTexture, scene);
  19257. // Update Sampling Mode
  19258. if (parsedTexture.samplingMode) {
  19259. var sampling = parsedTexture.samplingMode;
  19260. if (texture._samplingMode !== sampling) {
  19261. texture.updateSamplingMode(sampling);
  19262. }
  19263. }
  19264. // Animations
  19265. if (parsedTexture.animations) {
  19266. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19267. var parsedAnimation = parsedTexture.animations[animationIndex];
  19268. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19269. }
  19270. }
  19271. return texture;
  19272. };
  19273. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19274. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19275. if (noMipmap === void 0) { noMipmap = false; }
  19276. if (invertY === void 0) { invertY = true; }
  19277. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19278. if (onLoad === void 0) { onLoad = null; }
  19279. if (onError === void 0) { onError = null; }
  19280. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19281. if (name.substr(0, 5) !== "data:") {
  19282. name = "data:" + name;
  19283. }
  19284. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19285. };
  19286. return Texture;
  19287. }(BABYLON.BaseTexture));
  19288. // Constants
  19289. Texture.NEAREST_SAMPLINGMODE = 1;
  19290. Texture.BILINEAR_SAMPLINGMODE = 2;
  19291. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19292. Texture.EXPLICIT_MODE = 0;
  19293. Texture.SPHERICAL_MODE = 1;
  19294. Texture.PLANAR_MODE = 2;
  19295. Texture.CUBIC_MODE = 3;
  19296. Texture.PROJECTION_MODE = 4;
  19297. Texture.SKYBOX_MODE = 5;
  19298. Texture.INVCUBIC_MODE = 6;
  19299. Texture.EQUIRECTANGULAR_MODE = 7;
  19300. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19301. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19302. Texture.CLAMP_ADDRESSMODE = 0;
  19303. Texture.WRAP_ADDRESSMODE = 1;
  19304. Texture.MIRROR_ADDRESSMODE = 2;
  19305. __decorate([
  19306. BABYLON.serialize()
  19307. ], Texture.prototype, "url", void 0);
  19308. __decorate([
  19309. BABYLON.serialize()
  19310. ], Texture.prototype, "uOffset", void 0);
  19311. __decorate([
  19312. BABYLON.serialize()
  19313. ], Texture.prototype, "vOffset", void 0);
  19314. __decorate([
  19315. BABYLON.serialize()
  19316. ], Texture.prototype, "uScale", void 0);
  19317. __decorate([
  19318. BABYLON.serialize()
  19319. ], Texture.prototype, "vScale", void 0);
  19320. __decorate([
  19321. BABYLON.serialize()
  19322. ], Texture.prototype, "uAng", void 0);
  19323. __decorate([
  19324. BABYLON.serialize()
  19325. ], Texture.prototype, "vAng", void 0);
  19326. __decorate([
  19327. BABYLON.serialize()
  19328. ], Texture.prototype, "wAng", void 0);
  19329. __decorate([
  19330. BABYLON.serialize()
  19331. ], Texture.prototype, "isBlocking", null);
  19332. BABYLON.Texture = Texture;
  19333. })(BABYLON || (BABYLON = {}));
  19334. //# sourceMappingURL=babylon.texture.js.map
  19335. var BABYLON;
  19336. (function (BABYLON) {
  19337. var _InstancesBatch = (function () {
  19338. function _InstancesBatch() {
  19339. this.mustReturn = false;
  19340. this.visibleInstances = new Array();
  19341. this.renderSelf = new Array();
  19342. }
  19343. return _InstancesBatch;
  19344. }());
  19345. BABYLON._InstancesBatch = _InstancesBatch;
  19346. var Mesh = (function (_super) {
  19347. __extends(Mesh, _super);
  19348. /**
  19349. * @constructor
  19350. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19351. * @param {Scene} scene The scene to add this mesh to.
  19352. * @param {Node} parent The parent of this mesh, if it has one
  19353. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19354. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19355. * When false, achieved by calling a clone(), also passing False.
  19356. * This will make creation of children, recursive.
  19357. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19358. */
  19359. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19360. if (parent === void 0) { parent = null; }
  19361. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19362. var _this = _super.call(this, name, scene) || this;
  19363. // Events
  19364. /**
  19365. * An event triggered before rendering the mesh
  19366. * @type {BABYLON.Observable}
  19367. */
  19368. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19369. /**
  19370. * An event triggered after rendering the mesh
  19371. * @type {BABYLON.Observable}
  19372. */
  19373. _this.onAfterRenderObservable = new BABYLON.Observable();
  19374. /**
  19375. * An event triggered before drawing the mesh
  19376. * @type {BABYLON.Observable}
  19377. */
  19378. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19379. // Members
  19380. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19381. _this.instances = new Array();
  19382. _this._LODLevels = new Array();
  19383. _this._visibleInstances = {};
  19384. _this._renderIdForInstances = new Array();
  19385. _this._batchCache = new _InstancesBatch();
  19386. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19387. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19388. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19389. // Will be used to save a source mesh reference, If any
  19390. _this._source = null;
  19391. if (source) {
  19392. // Source mesh
  19393. _this._source = source;
  19394. // Geometry
  19395. if (source._geometry) {
  19396. source._geometry.applyToMesh(_this);
  19397. }
  19398. // Deep copy
  19399. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19400. // Parent
  19401. _this.parent = source.parent;
  19402. // Pivot
  19403. _this.setPivotMatrix(source.getPivotMatrix());
  19404. _this.id = name + "." + source.id;
  19405. // Material
  19406. _this.material = source.material;
  19407. var index;
  19408. if (!doNotCloneChildren) {
  19409. // Children
  19410. for (index = 0; index < scene.meshes.length; index++) {
  19411. var mesh = scene.meshes[index];
  19412. if (mesh.parent === source) {
  19413. // doNotCloneChildren is always going to be False
  19414. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19415. }
  19416. }
  19417. }
  19418. // Physics clone
  19419. var physicsEngine = _this.getScene().getPhysicsEngine();
  19420. if (clonePhysicsImpostor && physicsEngine) {
  19421. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19422. if (impostor) {
  19423. _this.physicsImpostor = impostor.clone(_this);
  19424. }
  19425. }
  19426. // Particles
  19427. for (index = 0; index < scene.particleSystems.length; index++) {
  19428. var system = scene.particleSystems[index];
  19429. if (system.emitter === source) {
  19430. system.clone(system.name, _this);
  19431. }
  19432. }
  19433. _this.computeWorldMatrix(true);
  19434. }
  19435. // Parent
  19436. if (parent !== null) {
  19437. _this.parent = parent;
  19438. }
  19439. return _this;
  19440. }
  19441. Object.defineProperty(Mesh, "FRONTSIDE", {
  19442. /**
  19443. * Mesh side orientation : usually the external or front surface
  19444. */
  19445. get: function () {
  19446. return Mesh._FRONTSIDE;
  19447. },
  19448. enumerable: true,
  19449. configurable: true
  19450. });
  19451. Object.defineProperty(Mesh, "BACKSIDE", {
  19452. /**
  19453. * Mesh side orientation : usually the internal or back surface
  19454. */
  19455. get: function () {
  19456. return Mesh._BACKSIDE;
  19457. },
  19458. enumerable: true,
  19459. configurable: true
  19460. });
  19461. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19462. /**
  19463. * Mesh side orientation : both internal and external or front and back surfaces
  19464. */
  19465. get: function () {
  19466. return Mesh._DOUBLESIDE;
  19467. },
  19468. enumerable: true,
  19469. configurable: true
  19470. });
  19471. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19472. /**
  19473. * Mesh side orientation : by default, `FRONTSIDE`
  19474. */
  19475. get: function () {
  19476. return Mesh._DEFAULTSIDE;
  19477. },
  19478. enumerable: true,
  19479. configurable: true
  19480. });
  19481. Object.defineProperty(Mesh, "NO_CAP", {
  19482. /**
  19483. * Mesh cap setting : no cap
  19484. */
  19485. get: function () {
  19486. return Mesh._NO_CAP;
  19487. },
  19488. enumerable: true,
  19489. configurable: true
  19490. });
  19491. Object.defineProperty(Mesh, "CAP_START", {
  19492. /**
  19493. * Mesh cap setting : one cap at the beginning of the mesh
  19494. */
  19495. get: function () {
  19496. return Mesh._CAP_START;
  19497. },
  19498. enumerable: true,
  19499. configurable: true
  19500. });
  19501. Object.defineProperty(Mesh, "CAP_END", {
  19502. /**
  19503. * Mesh cap setting : one cap at the end of the mesh
  19504. */
  19505. get: function () {
  19506. return Mesh._CAP_END;
  19507. },
  19508. enumerable: true,
  19509. configurable: true
  19510. });
  19511. Object.defineProperty(Mesh, "CAP_ALL", {
  19512. /**
  19513. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19514. */
  19515. get: function () {
  19516. return Mesh._CAP_ALL;
  19517. },
  19518. enumerable: true,
  19519. configurable: true
  19520. });
  19521. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19522. set: function (callback) {
  19523. if (this._onBeforeDrawObserver) {
  19524. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19525. }
  19526. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19527. },
  19528. enumerable: true,
  19529. configurable: true
  19530. });
  19531. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19532. get: function () {
  19533. return this._morphTargetManager;
  19534. },
  19535. set: function (value) {
  19536. if (this._morphTargetManager === value) {
  19537. return;
  19538. }
  19539. this._morphTargetManager = value;
  19540. this._syncGeometryWithMorphTargetManager();
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. Object.defineProperty(Mesh.prototype, "source", {
  19546. get: function () {
  19547. return this._source;
  19548. },
  19549. enumerable: true,
  19550. configurable: true
  19551. });
  19552. // Methods
  19553. /**
  19554. * Returns the string "Mesh".
  19555. */
  19556. Mesh.prototype.getClassName = function () {
  19557. return "Mesh";
  19558. };
  19559. /**
  19560. * Returns a string.
  19561. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19562. */
  19563. Mesh.prototype.toString = function (fullDetails) {
  19564. var ret = _super.prototype.toString.call(this, fullDetails);
  19565. ret += ", n vertices: " + this.getTotalVertices();
  19566. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19567. if (this.animations) {
  19568. for (var i = 0; i < this.animations.length; i++) {
  19569. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19570. }
  19571. }
  19572. if (fullDetails) {
  19573. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19574. }
  19575. return ret;
  19576. };
  19577. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19578. /**
  19579. * True if the mesh has some Levels Of Details (LOD).
  19580. * Returns a boolean.
  19581. */
  19582. get: function () {
  19583. return this._LODLevels.length > 0;
  19584. },
  19585. enumerable: true,
  19586. configurable: true
  19587. });
  19588. Mesh.prototype._sortLODLevels = function () {
  19589. this._LODLevels.sort(function (a, b) {
  19590. if (a.distance < b.distance) {
  19591. return 1;
  19592. }
  19593. if (a.distance > b.distance) {
  19594. return -1;
  19595. }
  19596. return 0;
  19597. });
  19598. };
  19599. /**
  19600. * Add a mesh as LOD level triggered at the given distance.
  19601. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19602. * @param {number} distance The distance from the center of the object to show this level
  19603. * @param {Mesh} mesh The mesh to be added as LOD level
  19604. * @return {Mesh} This mesh (for chaining)
  19605. */
  19606. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19607. if (mesh && mesh._masterMesh) {
  19608. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19609. return this;
  19610. }
  19611. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19612. this._LODLevels.push(level);
  19613. if (mesh) {
  19614. mesh._masterMesh = this;
  19615. }
  19616. this._sortLODLevels();
  19617. return this;
  19618. };
  19619. /**
  19620. * Returns the LOD level mesh at the passed distance or null if not found.
  19621. * It is related to the method `addLODLevel(distance, mesh)`.
  19622. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19623. * Returns an object Mesh or `null`.
  19624. */
  19625. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19626. for (var index = 0; index < this._LODLevels.length; index++) {
  19627. var level = this._LODLevels[index];
  19628. if (level.distance === distance) {
  19629. return level.mesh;
  19630. }
  19631. }
  19632. return null;
  19633. };
  19634. /**
  19635. * Remove a mesh from the LOD array
  19636. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19637. * @param {Mesh} mesh The mesh to be removed.
  19638. * @return {Mesh} This mesh (for chaining)
  19639. */
  19640. Mesh.prototype.removeLODLevel = function (mesh) {
  19641. for (var index = 0; index < this._LODLevels.length; index++) {
  19642. if (this._LODLevels[index].mesh === mesh) {
  19643. this._LODLevels.splice(index, 1);
  19644. if (mesh) {
  19645. mesh._masterMesh = null;
  19646. }
  19647. }
  19648. }
  19649. this._sortLODLevels();
  19650. return this;
  19651. };
  19652. /**
  19653. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19654. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19655. */
  19656. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19657. if (!this._LODLevels || this._LODLevels.length === 0) {
  19658. return this;
  19659. }
  19660. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19661. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19662. if (this.onLODLevelSelection) {
  19663. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19664. }
  19665. return this;
  19666. }
  19667. for (var index = 0; index < this._LODLevels.length; index++) {
  19668. var level = this._LODLevels[index];
  19669. if (level.distance < distanceToCamera) {
  19670. if (level.mesh) {
  19671. level.mesh._preActivate();
  19672. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19673. }
  19674. if (this.onLODLevelSelection) {
  19675. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19676. }
  19677. return level.mesh;
  19678. }
  19679. }
  19680. if (this.onLODLevelSelection) {
  19681. this.onLODLevelSelection(distanceToCamera, this, this);
  19682. }
  19683. return this;
  19684. };
  19685. Object.defineProperty(Mesh.prototype, "geometry", {
  19686. /**
  19687. * Returns the mesh internal Geometry object.
  19688. */
  19689. get: function () {
  19690. return this._geometry;
  19691. },
  19692. enumerable: true,
  19693. configurable: true
  19694. });
  19695. /**
  19696. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19697. */
  19698. Mesh.prototype.getTotalVertices = function () {
  19699. if (!this._geometry) {
  19700. return 0;
  19701. }
  19702. return this._geometry.getTotalVertices();
  19703. };
  19704. /**
  19705. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19706. * 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.
  19707. * You can force the copy with forceCopy === true
  19708. * Returns null if the mesh has no geometry or no vertex buffer.
  19709. * Possible `kind` values :
  19710. * - BABYLON.VertexBuffer.PositionKind
  19711. * - BABYLON.VertexBuffer.UVKind
  19712. * - BABYLON.VertexBuffer.UV2Kind
  19713. * - BABYLON.VertexBuffer.UV3Kind
  19714. * - BABYLON.VertexBuffer.UV4Kind
  19715. * - BABYLON.VertexBuffer.UV5Kind
  19716. * - BABYLON.VertexBuffer.UV6Kind
  19717. * - BABYLON.VertexBuffer.ColorKind
  19718. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19719. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19720. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19721. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19722. */
  19723. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19724. if (!this._geometry) {
  19725. return null;
  19726. }
  19727. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19728. };
  19729. /**
  19730. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19731. * Returns `undefined` if the mesh has no geometry.
  19732. * Possible `kind` values :
  19733. * - BABYLON.VertexBuffer.PositionKind
  19734. * - BABYLON.VertexBuffer.UVKind
  19735. * - BABYLON.VertexBuffer.UV2Kind
  19736. * - BABYLON.VertexBuffer.UV3Kind
  19737. * - BABYLON.VertexBuffer.UV4Kind
  19738. * - BABYLON.VertexBuffer.UV5Kind
  19739. * - BABYLON.VertexBuffer.UV6Kind
  19740. * - BABYLON.VertexBuffer.ColorKind
  19741. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19742. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19743. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19744. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19745. */
  19746. Mesh.prototype.getVertexBuffer = function (kind) {
  19747. if (!this._geometry) {
  19748. return undefined;
  19749. }
  19750. return this._geometry.getVertexBuffer(kind);
  19751. };
  19752. /**
  19753. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19754. * Possible `kind` values :
  19755. * - BABYLON.VertexBuffer.PositionKind
  19756. * - BABYLON.VertexBuffer.UVKind
  19757. * - BABYLON.VertexBuffer.UV2Kind
  19758. * - BABYLON.VertexBuffer.UV3Kind
  19759. * - BABYLON.VertexBuffer.UV4Kind
  19760. * - BABYLON.VertexBuffer.UV5Kind
  19761. * - BABYLON.VertexBuffer.UV6Kind
  19762. * - BABYLON.VertexBuffer.ColorKind
  19763. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19764. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19765. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19766. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19767. */
  19768. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19769. if (!this._geometry) {
  19770. if (this._delayInfo) {
  19771. return this._delayInfo.indexOf(kind) !== -1;
  19772. }
  19773. return false;
  19774. }
  19775. return this._geometry.isVerticesDataPresent(kind);
  19776. };
  19777. /**
  19778. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19779. * Possible `kind` values :
  19780. * - BABYLON.VertexBuffer.PositionKind
  19781. * - BABYLON.VertexBuffer.UVKind
  19782. * - BABYLON.VertexBuffer.UV2Kind
  19783. * - BABYLON.VertexBuffer.UV3Kind
  19784. * - BABYLON.VertexBuffer.UV4Kind
  19785. * - BABYLON.VertexBuffer.UV5Kind
  19786. * - BABYLON.VertexBuffer.UV6Kind
  19787. * - BABYLON.VertexBuffer.ColorKind
  19788. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19789. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19790. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19791. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19792. */
  19793. Mesh.prototype.getVerticesDataKinds = function () {
  19794. if (!this._geometry) {
  19795. var result = [];
  19796. if (this._delayInfo) {
  19797. this._delayInfo.forEach(function (kind, index, array) {
  19798. result.push(kind);
  19799. });
  19800. }
  19801. return result;
  19802. }
  19803. return this._geometry.getVerticesDataKinds();
  19804. };
  19805. /**
  19806. * Returns a positive integer : the total number of indices in this mesh geometry.
  19807. * Returns zero if the mesh has no geometry.
  19808. */
  19809. Mesh.prototype.getTotalIndices = function () {
  19810. if (!this._geometry) {
  19811. return 0;
  19812. }
  19813. return this._geometry.getTotalIndices();
  19814. };
  19815. /**
  19816. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  19817. * 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.
  19818. * Returns an empty array if the mesh has no geometry.
  19819. */
  19820. Mesh.prototype.getIndices = function (copyWhenShared) {
  19821. if (!this._geometry) {
  19822. return [];
  19823. }
  19824. return this._geometry.getIndices(copyWhenShared);
  19825. };
  19826. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19827. get: function () {
  19828. return this._masterMesh !== null && this._masterMesh !== undefined;
  19829. },
  19830. enumerable: true,
  19831. configurable: true
  19832. });
  19833. /**
  19834. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19835. */
  19836. Mesh.prototype.isReady = function () {
  19837. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19838. return false;
  19839. }
  19840. return _super.prototype.isReady.call(this);
  19841. };
  19842. /**
  19843. * Boolean : true if the mesh has been disposed.
  19844. */
  19845. Mesh.prototype.isDisposed = function () {
  19846. return this._isDisposed;
  19847. };
  19848. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19849. get: function () {
  19850. return this._sideOrientation;
  19851. },
  19852. /**
  19853. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19854. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19855. */
  19856. set: function (sideO) {
  19857. this._sideOrientation = sideO;
  19858. },
  19859. enumerable: true,
  19860. configurable: true
  19861. });
  19862. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19863. /**
  19864. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19865. * This property is pertinent only for updatable parametric shapes.
  19866. */
  19867. get: function () {
  19868. return this._areNormalsFrozen;
  19869. },
  19870. enumerable: true,
  19871. configurable: true
  19872. });
  19873. /**
  19874. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19875. * It has no effect at all on other shapes.
  19876. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19877. * Returns the Mesh.
  19878. */
  19879. Mesh.prototype.freezeNormals = function () {
  19880. this._areNormalsFrozen = true;
  19881. return this;
  19882. };
  19883. /**
  19884. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19885. * It has no effect at all on other shapes.
  19886. * It reactivates the mesh normals computation if it was previously frozen.
  19887. * Returns the Mesh.
  19888. */
  19889. Mesh.prototype.unfreezeNormals = function () {
  19890. this._areNormalsFrozen = false;
  19891. return this;
  19892. };
  19893. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19894. /**
  19895. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19896. */
  19897. set: function (count) {
  19898. this._overridenInstanceCount = count;
  19899. },
  19900. enumerable: true,
  19901. configurable: true
  19902. });
  19903. // Methods
  19904. Mesh.prototype._preActivate = function () {
  19905. var sceneRenderId = this.getScene().getRenderId();
  19906. if (this._preActivateId === sceneRenderId) {
  19907. return this;
  19908. }
  19909. this._preActivateId = sceneRenderId;
  19910. this._visibleInstances = null;
  19911. return this;
  19912. };
  19913. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19914. if (this._visibleInstances) {
  19915. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19916. }
  19917. return this;
  19918. };
  19919. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19920. if (!this._visibleInstances) {
  19921. this._visibleInstances = {};
  19922. this._visibleInstances.defaultRenderId = renderId;
  19923. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19924. }
  19925. if (!this._visibleInstances[renderId]) {
  19926. this._visibleInstances[renderId] = new Array();
  19927. }
  19928. this._visibleInstances[renderId].push(instance);
  19929. return this;
  19930. };
  19931. /**
  19932. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19933. * This means the mesh underlying bounding box and sphere are recomputed.
  19934. * Returns the Mesh.
  19935. */
  19936. Mesh.prototype.refreshBoundingInfo = function () {
  19937. if (this._boundingInfo.isLocked) {
  19938. return;
  19939. }
  19940. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19941. if (data) {
  19942. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19943. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19944. }
  19945. if (this.subMeshes) {
  19946. for (var index = 0; index < this.subMeshes.length; index++) {
  19947. this.subMeshes[index].refreshBoundingInfo();
  19948. }
  19949. }
  19950. this._updateBoundingInfo();
  19951. return this;
  19952. };
  19953. Mesh.prototype._createGlobalSubMesh = function () {
  19954. var totalVertices = this.getTotalVertices();
  19955. if (!totalVertices || !this.getIndices()) {
  19956. return null;
  19957. }
  19958. this.releaseSubMeshes();
  19959. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19960. };
  19961. Mesh.prototype.subdivide = function (count) {
  19962. if (count < 1) {
  19963. return;
  19964. }
  19965. var totalIndices = this.getTotalIndices();
  19966. var subdivisionSize = (totalIndices / count) | 0;
  19967. var offset = 0;
  19968. // Ensure that subdivisionSize is a multiple of 3
  19969. while (subdivisionSize % 3 !== 0) {
  19970. subdivisionSize++;
  19971. }
  19972. this.releaseSubMeshes();
  19973. for (var index = 0; index < count; index++) {
  19974. if (offset >= totalIndices) {
  19975. break;
  19976. }
  19977. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19978. offset += subdivisionSize;
  19979. }
  19980. this.synchronizeInstances();
  19981. };
  19982. /**
  19983. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19984. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19985. * The `data` are either a numeric array either a Float32Array.
  19986. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19987. * 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).
  19988. * Note that a new underlying VertexBuffer object is created each call.
  19989. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19990. *
  19991. * Possible `kind` values :
  19992. * - BABYLON.VertexBuffer.PositionKind
  19993. * - BABYLON.VertexBuffer.UVKind
  19994. * - BABYLON.VertexBuffer.UV2Kind
  19995. * - BABYLON.VertexBuffer.UV3Kind
  19996. * - BABYLON.VertexBuffer.UV4Kind
  19997. * - BABYLON.VertexBuffer.UV5Kind
  19998. * - BABYLON.VertexBuffer.UV6Kind
  19999. * - BABYLON.VertexBuffer.ColorKind
  20000. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20001. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20002. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20003. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20004. *
  20005. * Returns the Mesh.
  20006. */
  20007. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20008. if (!this._geometry) {
  20009. var vertexData = new BABYLON.VertexData();
  20010. vertexData.set(data, kind);
  20011. var scene = this.getScene();
  20012. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20013. }
  20014. else {
  20015. this._geometry.setVerticesData(kind, data, updatable, stride);
  20016. }
  20017. return this;
  20018. };
  20019. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20020. if (updatable === void 0) { updatable = true; }
  20021. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20022. return;
  20023. }
  20024. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20025. };
  20026. /**
  20027. * Sets the mesh VertexBuffer.
  20028. * Returns the Mesh.
  20029. */
  20030. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20031. if (!this._geometry) {
  20032. var scene = this.getScene();
  20033. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20034. }
  20035. this._geometry.setVerticesBuffer(buffer);
  20036. return this;
  20037. };
  20038. /**
  20039. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20040. * If the mesh has no geometry, it is simply returned as it is.
  20041. * The `data` are either a numeric array either a Float32Array.
  20042. * No new underlying VertexBuffer object is created.
  20043. * 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.
  20044. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20045. *
  20046. * Possible `kind` values :
  20047. * - BABYLON.VertexBuffer.PositionKind
  20048. * - BABYLON.VertexBuffer.UVKind
  20049. * - BABYLON.VertexBuffer.UV2Kind
  20050. * - BABYLON.VertexBuffer.UV3Kind
  20051. * - BABYLON.VertexBuffer.UV4Kind
  20052. * - BABYLON.VertexBuffer.UV5Kind
  20053. * - BABYLON.VertexBuffer.UV6Kind
  20054. * - BABYLON.VertexBuffer.ColorKind
  20055. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20056. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20057. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20058. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20059. *
  20060. * Returns the Mesh.
  20061. */
  20062. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20063. if (!this._geometry) {
  20064. return;
  20065. }
  20066. if (!makeItUnique) {
  20067. this._geometry.updateVerticesData(kind, data, updateExtends);
  20068. }
  20069. else {
  20070. this.makeGeometryUnique();
  20071. this.updateVerticesData(kind, data, updateExtends, false);
  20072. }
  20073. return this;
  20074. };
  20075. /**
  20076. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20077. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20078. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20079. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20080. * Returns the Mesh.
  20081. */
  20082. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20083. if (computeNormals === void 0) { computeNormals = true; }
  20084. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20085. positionFunction(positions);
  20086. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20087. if (computeNormals) {
  20088. var indices = this.getIndices();
  20089. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20090. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20091. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20092. }
  20093. return this;
  20094. };
  20095. /**
  20096. * This method will force the computation of normals for the mesh.
  20097. * Please note that the mesh must have normals vertex data already.
  20098. * Returns the Mesh.
  20099. */
  20100. Mesh.prototype.recomputeNormals = function (markDataAsUpdatable) {
  20101. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20102. var indices = this.getIndices();
  20103. var normals;
  20104. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20105. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20106. }
  20107. else {
  20108. normals = [];
  20109. }
  20110. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20111. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, markDataAsUpdatable);
  20112. return this;
  20113. };
  20114. /**
  20115. * Creates a un-shared specific occurence of the geometry for the mesh.
  20116. * Returns the Mesh.
  20117. */
  20118. Mesh.prototype.makeGeometryUnique = function () {
  20119. if (!this._geometry) {
  20120. return;
  20121. }
  20122. var oldGeometry = this._geometry;
  20123. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20124. oldGeometry.releaseForMesh(this, true);
  20125. geometry.applyToMesh(this);
  20126. return this;
  20127. };
  20128. /**
  20129. * Sets the mesh indices.
  20130. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20131. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20132. * This method creates a new index buffer each call.
  20133. * Returns the Mesh.
  20134. */
  20135. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20136. if (!this._geometry) {
  20137. var vertexData = new BABYLON.VertexData();
  20138. vertexData.indices = indices;
  20139. var scene = this.getScene();
  20140. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20141. }
  20142. else {
  20143. this._geometry.setIndices(indices, totalVertices);
  20144. }
  20145. return this;
  20146. };
  20147. /**
  20148. * Invert the geometry to move from a right handed system to a left handed one.
  20149. * Returns the Mesh.
  20150. */
  20151. Mesh.prototype.toLeftHanded = function () {
  20152. if (!this._geometry) {
  20153. return;
  20154. }
  20155. this._geometry.toLeftHanded();
  20156. return this;
  20157. };
  20158. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20159. var engine = this.getScene().getEngine();
  20160. // Wireframe
  20161. var indexToBind;
  20162. if (this._unIndexed) {
  20163. indexToBind = null;
  20164. }
  20165. else {
  20166. switch (fillMode) {
  20167. case BABYLON.Material.PointFillMode:
  20168. indexToBind = null;
  20169. break;
  20170. case BABYLON.Material.WireFrameFillMode:
  20171. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20172. break;
  20173. default:
  20174. case BABYLON.Material.TriangleFillMode:
  20175. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20176. break;
  20177. }
  20178. }
  20179. // VBOs
  20180. this._geometry._bind(effect, indexToBind);
  20181. return this;
  20182. };
  20183. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20184. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20185. return this;
  20186. }
  20187. this.onBeforeDrawObservable.notifyObservers(this);
  20188. var engine = this.getScene().getEngine();
  20189. // Draw order
  20190. switch (fillMode) {
  20191. case BABYLON.Material.PointFillMode:
  20192. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20193. break;
  20194. case BABYLON.Material.WireFrameFillMode:
  20195. if (this._unIndexed) {
  20196. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20197. }
  20198. else {
  20199. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20200. }
  20201. break;
  20202. default:
  20203. if (this._unIndexed) {
  20204. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20205. }
  20206. else {
  20207. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20208. }
  20209. }
  20210. return this;
  20211. };
  20212. /**
  20213. * Registers for this mesh a javascript function called just before the rendering process.
  20214. * This function is passed the current mesh.
  20215. * Return the Mesh.
  20216. */
  20217. Mesh.prototype.registerBeforeRender = function (func) {
  20218. this.onBeforeRenderObservable.add(func);
  20219. return this;
  20220. };
  20221. /**
  20222. * Disposes a previously registered javascript function called before the rendering.
  20223. * This function is passed the current mesh.
  20224. * Returns the Mesh.
  20225. */
  20226. Mesh.prototype.unregisterBeforeRender = function (func) {
  20227. this.onBeforeRenderObservable.removeCallback(func);
  20228. return this;
  20229. };
  20230. /**
  20231. * Registers for this mesh a javascript function called just after the rendering is complete.
  20232. * This function is passed the current mesh.
  20233. * Returns the Mesh.
  20234. */
  20235. Mesh.prototype.registerAfterRender = function (func) {
  20236. this.onAfterRenderObservable.add(func);
  20237. return this;
  20238. };
  20239. /**
  20240. * Disposes a previously registered javascript function called after the rendering.
  20241. * This function is passed the current mesh.
  20242. * Return the Mesh.
  20243. */
  20244. Mesh.prototype.unregisterAfterRender = function (func) {
  20245. this.onAfterRenderObservable.removeCallback(func);
  20246. return this;
  20247. };
  20248. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20249. var scene = this.getScene();
  20250. this._batchCache.mustReturn = false;
  20251. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20252. this._batchCache.visibleInstances[subMeshId] = null;
  20253. if (this._visibleInstances) {
  20254. var currentRenderId = scene.getRenderId();
  20255. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20256. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20257. var selfRenderId = this._renderId;
  20258. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20259. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20260. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20261. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20262. }
  20263. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20264. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20265. this._batchCache.mustReturn = true;
  20266. return this._batchCache;
  20267. }
  20268. if (currentRenderId !== selfRenderId) {
  20269. this._batchCache.renderSelf[subMeshId] = false;
  20270. }
  20271. }
  20272. this._renderIdForInstances[subMeshId] = currentRenderId;
  20273. }
  20274. return this._batchCache;
  20275. };
  20276. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20277. var visibleInstances = batch.visibleInstances[subMesh._id];
  20278. var matricesCount = visibleInstances.length + 1;
  20279. var bufferSize = matricesCount * 16 * 4;
  20280. var currentInstancesBufferSize = this._instancesBufferSize;
  20281. var instancesBuffer = this._instancesBuffer;
  20282. while (this._instancesBufferSize < bufferSize) {
  20283. this._instancesBufferSize *= 2;
  20284. }
  20285. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20286. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20287. }
  20288. var offset = 0;
  20289. var instancesCount = 0;
  20290. var world = this.getWorldMatrix();
  20291. if (batch.renderSelf[subMesh._id]) {
  20292. world.copyToArray(this._instancesData, offset);
  20293. offset += 16;
  20294. instancesCount++;
  20295. }
  20296. if (visibleInstances) {
  20297. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20298. var instance = visibleInstances[instanceIndex];
  20299. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20300. offset += 16;
  20301. instancesCount++;
  20302. }
  20303. }
  20304. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20305. if (instancesBuffer) {
  20306. instancesBuffer.dispose();
  20307. }
  20308. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20309. this._instancesBuffer = instancesBuffer;
  20310. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20311. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20312. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20313. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20314. }
  20315. else {
  20316. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20317. }
  20318. this.geometry._bind(effect);
  20319. this._draw(subMesh, fillMode, instancesCount);
  20320. engine.unbindInstanceAttributes();
  20321. return this;
  20322. };
  20323. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20324. var scene = this.getScene();
  20325. var engine = scene.getEngine();
  20326. if (hardwareInstancedRendering) {
  20327. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20328. }
  20329. else {
  20330. if (batch.renderSelf[subMesh._id]) {
  20331. // Draw
  20332. if (onBeforeDraw) {
  20333. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20334. }
  20335. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20336. }
  20337. if (batch.visibleInstances[subMesh._id]) {
  20338. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20339. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20340. // World
  20341. var world = instance.getWorldMatrix();
  20342. if (onBeforeDraw) {
  20343. onBeforeDraw(true, world, effectiveMaterial);
  20344. }
  20345. // Draw
  20346. this._draw(subMesh, fillMode);
  20347. }
  20348. }
  20349. }
  20350. return this;
  20351. };
  20352. /**
  20353. * Triggers the draw call for the mesh.
  20354. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20355. * Returns the Mesh.
  20356. */
  20357. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20358. var scene = this.getScene();
  20359. // Managing instances
  20360. var batch = this._getInstancesRenderList(subMesh._id);
  20361. if (batch.mustReturn) {
  20362. return this;
  20363. }
  20364. // Checking geometry state
  20365. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20366. return this;
  20367. }
  20368. var callbackIndex;
  20369. this.onBeforeRenderObservable.notifyObservers(this);
  20370. var engine = scene.getEngine();
  20371. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20372. // Material
  20373. var effectiveMaterial = subMesh.getMaterial();
  20374. if (!effectiveMaterial) {
  20375. return this;
  20376. }
  20377. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20378. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20379. return this;
  20380. }
  20381. }
  20382. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20383. return this;
  20384. }
  20385. // Alpha mode
  20386. if (enableAlphaMode) {
  20387. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20388. }
  20389. // Outline - step 1
  20390. var savedDepthWrite = engine.getDepthWrite();
  20391. if (this.renderOutline) {
  20392. engine.setDepthWrite(false);
  20393. scene.getOutlineRenderer().render(subMesh, batch);
  20394. engine.setDepthWrite(savedDepthWrite);
  20395. }
  20396. var effect;
  20397. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20398. effect = subMesh.effect;
  20399. }
  20400. else {
  20401. effect = effectiveMaterial.getEffect();
  20402. }
  20403. effectiveMaterial._preBind(effect);
  20404. // Bind
  20405. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20406. this._bind(subMesh, effect, fillMode);
  20407. var world = this.getWorldMatrix();
  20408. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20409. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20410. }
  20411. else {
  20412. effectiveMaterial.bind(world, this);
  20413. }
  20414. // Draw
  20415. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20416. // Unbind
  20417. effectiveMaterial.unbind();
  20418. // Outline - step 2
  20419. if (this.renderOutline && savedDepthWrite) {
  20420. engine.setDepthWrite(true);
  20421. engine.setColorWrite(false);
  20422. scene.getOutlineRenderer().render(subMesh, batch);
  20423. engine.setColorWrite(true);
  20424. }
  20425. // Overlay
  20426. if (this.renderOverlay) {
  20427. var currentMode = engine.getAlphaMode();
  20428. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20429. scene.getOutlineRenderer().render(subMesh, batch, true);
  20430. engine.setAlphaMode(currentMode);
  20431. }
  20432. this.onAfterRenderObservable.notifyObservers(this);
  20433. return this;
  20434. };
  20435. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20436. if (isInstance) {
  20437. effectiveMaterial.bindOnlyWorldMatrix(world);
  20438. }
  20439. return this;
  20440. };
  20441. /**
  20442. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20443. */
  20444. Mesh.prototype.getEmittedParticleSystems = function () {
  20445. var results = new Array();
  20446. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20447. var particleSystem = this.getScene().particleSystems[index];
  20448. if (particleSystem.emitter === this) {
  20449. results.push(particleSystem);
  20450. }
  20451. }
  20452. return results;
  20453. };
  20454. /**
  20455. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20456. */
  20457. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20458. var results = new Array();
  20459. var descendants = this.getDescendants();
  20460. descendants.push(this);
  20461. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20462. var particleSystem = this.getScene().particleSystems[index];
  20463. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20464. results.push(particleSystem);
  20465. }
  20466. }
  20467. return results;
  20468. };
  20469. Mesh.prototype._checkDelayState = function () {
  20470. var scene = this.getScene();
  20471. if (this._geometry) {
  20472. this._geometry.load(scene);
  20473. }
  20474. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20475. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20476. this._queueLoad(this, scene);
  20477. }
  20478. return this;
  20479. };
  20480. Mesh.prototype._queueLoad = function (mesh, scene) {
  20481. var _this = this;
  20482. scene._addPendingData(mesh);
  20483. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20484. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20485. if (data instanceof ArrayBuffer) {
  20486. _this._delayLoadingFunction(data, _this);
  20487. }
  20488. else {
  20489. _this._delayLoadingFunction(JSON.parse(data), _this);
  20490. }
  20491. _this.instances.forEach(function (instance) {
  20492. instance._syncSubMeshes();
  20493. });
  20494. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20495. scene._removePendingData(_this);
  20496. }, function () { }, scene.database, getBinaryData);
  20497. return this;
  20498. };
  20499. /**
  20500. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20501. */
  20502. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20503. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20504. return false;
  20505. }
  20506. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20507. return false;
  20508. }
  20509. this._checkDelayState();
  20510. return true;
  20511. };
  20512. /**
  20513. * Sets the mesh material by the material or multiMaterial `id` property.
  20514. * The material `id` is a string identifying the material or the multiMaterial.
  20515. * This method returns the Mesh.
  20516. */
  20517. Mesh.prototype.setMaterialByID = function (id) {
  20518. var materials = this.getScene().materials;
  20519. var index;
  20520. for (index = materials.length - 1; index > -1; index--) {
  20521. if (materials[index].id === id) {
  20522. this.material = materials[index];
  20523. return this;
  20524. }
  20525. }
  20526. // Multi
  20527. var multiMaterials = this.getScene().multiMaterials;
  20528. for (index = multiMaterials.length - 1; index > -1; index--) {
  20529. if (multiMaterials[index].id === id) {
  20530. this.material = multiMaterials[index];
  20531. return this;
  20532. }
  20533. }
  20534. return this;
  20535. };
  20536. /**
  20537. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20538. */
  20539. Mesh.prototype.getAnimatables = function () {
  20540. var results = [];
  20541. if (this.material) {
  20542. results.push(this.material);
  20543. }
  20544. if (this.skeleton) {
  20545. results.push(this.skeleton);
  20546. }
  20547. return results;
  20548. };
  20549. /**
  20550. * Modifies the mesh geometry according to the passed transformation matrix.
  20551. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20552. * The mesh normals are modified accordingly the same transformation.
  20553. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20554. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20555. * Returns the Mesh.
  20556. */
  20557. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20558. // Position
  20559. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20560. return this;
  20561. }
  20562. var submeshes = this.subMeshes.splice(0);
  20563. this._resetPointsArrayCache();
  20564. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20565. var temp = [];
  20566. var index;
  20567. for (index = 0; index < data.length; index += 3) {
  20568. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20569. }
  20570. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20571. // Normals
  20572. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20573. return this;
  20574. }
  20575. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20576. temp = [];
  20577. for (index = 0; index < data.length; index += 3) {
  20578. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20579. }
  20580. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20581. // flip faces?
  20582. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20583. this.flipFaces();
  20584. }
  20585. // Restore submeshes
  20586. this.releaseSubMeshes();
  20587. this.subMeshes = submeshes;
  20588. return this;
  20589. };
  20590. /**
  20591. * Modifies the mesh geometry according to its own current World Matrix.
  20592. * The mesh World Matrix is then reset.
  20593. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20594. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20595. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20596. * Returns the Mesh.
  20597. */
  20598. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20599. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20600. this.scaling.copyFromFloats(1, 1, 1);
  20601. this.position.copyFromFloats(0, 0, 0);
  20602. this.rotation.copyFromFloats(0, 0, 0);
  20603. //only if quaternion is already set
  20604. if (this.rotationQuaternion) {
  20605. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20606. }
  20607. this._worldMatrix = BABYLON.Matrix.Identity();
  20608. return this;
  20609. };
  20610. Object.defineProperty(Mesh.prototype, "_positions", {
  20611. // Cache
  20612. get: function () {
  20613. if (this._geometry) {
  20614. return this._geometry._positions;
  20615. }
  20616. return null;
  20617. },
  20618. enumerable: true,
  20619. configurable: true
  20620. });
  20621. Mesh.prototype._resetPointsArrayCache = function () {
  20622. if (this._geometry) {
  20623. this._geometry._resetPointsArrayCache();
  20624. }
  20625. return this;
  20626. };
  20627. Mesh.prototype._generatePointsArray = function () {
  20628. if (this._geometry) {
  20629. return this._geometry._generatePointsArray();
  20630. }
  20631. return false;
  20632. };
  20633. /**
  20634. * Returns a new Mesh object generated from the current mesh properties.
  20635. * This method must not get confused with createInstance().
  20636. * The parameter `name` is a string, the name given to the new mesh.
  20637. * The optional parameter `newParent` can be any Node object (default `null`).
  20638. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20639. * 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.
  20640. */
  20641. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20642. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20643. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20644. };
  20645. /**
  20646. * Disposes the mesh.
  20647. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20648. */
  20649. Mesh.prototype.dispose = function (doNotRecurse) {
  20650. var _this = this;
  20651. this.morphTargetManager = undefined;
  20652. if (this._geometry) {
  20653. this._geometry.releaseForMesh(this, true);
  20654. }
  20655. // Sources
  20656. var meshes = this.getScene().meshes;
  20657. meshes.forEach(function (mesh) {
  20658. if (mesh._source && mesh._source === _this) {
  20659. mesh._source = null;
  20660. }
  20661. });
  20662. this._source = null;
  20663. // Instances
  20664. if (this._instancesBuffer) {
  20665. this._instancesBuffer.dispose();
  20666. this._instancesBuffer = null;
  20667. }
  20668. while (this.instances.length) {
  20669. this.instances[0].dispose();
  20670. }
  20671. // Highlight layers.
  20672. var highlightLayers = this.getScene().highlightLayers;
  20673. for (var i = 0; i < highlightLayers.length; i++) {
  20674. var highlightLayer = highlightLayers[i];
  20675. if (highlightLayer) {
  20676. highlightLayer.removeMesh(this);
  20677. highlightLayer.removeExcludedMesh(this);
  20678. }
  20679. }
  20680. _super.prototype.dispose.call(this, doNotRecurse);
  20681. };
  20682. /**
  20683. * Modifies the mesh geometry according to a displacement map.
  20684. * 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.
  20685. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20686. * This method returns nothing.
  20687. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20688. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20689. * 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.
  20690. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20691. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20692. *
  20693. * Returns the Mesh.
  20694. */
  20695. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20696. var _this = this;
  20697. var scene = this.getScene();
  20698. var onload = function (img) {
  20699. // Getting height map data
  20700. var canvas = document.createElement("canvas");
  20701. var context = canvas.getContext("2d");
  20702. var heightMapWidth = img.width;
  20703. var heightMapHeight = img.height;
  20704. canvas.width = heightMapWidth;
  20705. canvas.height = heightMapHeight;
  20706. context.drawImage(img, 0, 0);
  20707. // Create VertexData from map data
  20708. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20709. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20710. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20711. //execute success callback, if set
  20712. if (onSuccess) {
  20713. onSuccess(_this);
  20714. }
  20715. };
  20716. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20717. return this;
  20718. };
  20719. /**
  20720. * Modifies the mesh geometry according to a displacementMap buffer.
  20721. * 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.
  20722. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20723. * This method returns nothing.
  20724. * 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.
  20725. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20726. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20727. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20728. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20729. *
  20730. * Returns the Mesh.
  20731. */
  20732. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20733. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20734. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20735. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20736. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20737. return this;
  20738. }
  20739. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20740. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20741. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20742. var position = BABYLON.Vector3.Zero();
  20743. var normal = BABYLON.Vector3.Zero();
  20744. var uv = BABYLON.Vector2.Zero();
  20745. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20746. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20747. for (var index = 0; index < positions.length; index += 3) {
  20748. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20749. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20750. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20751. // Compute height
  20752. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20753. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20754. var pos = (u + v * heightMapWidth) * 4;
  20755. var r = buffer[pos] / 255.0;
  20756. var g = buffer[pos + 1] / 255.0;
  20757. var b = buffer[pos + 2] / 255.0;
  20758. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20759. normal.normalize();
  20760. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20761. position = position.add(normal);
  20762. position.toArray(positions, index);
  20763. }
  20764. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20765. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20766. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20767. return this;
  20768. };
  20769. /**
  20770. * Modify the mesh to get a flat shading rendering.
  20771. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20772. * This method returns the Mesh.
  20773. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20774. */
  20775. Mesh.prototype.convertToFlatShadedMesh = function () {
  20776. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20777. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20778. var kinds = this.getVerticesDataKinds();
  20779. var vbs = [];
  20780. var data = [];
  20781. var newdata = [];
  20782. var updatableNormals = false;
  20783. var kindIndex;
  20784. var kind;
  20785. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20786. kind = kinds[kindIndex];
  20787. var vertexBuffer = this.getVertexBuffer(kind);
  20788. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20789. updatableNormals = vertexBuffer.isUpdatable();
  20790. kinds.splice(kindIndex, 1);
  20791. kindIndex--;
  20792. continue;
  20793. }
  20794. vbs[kind] = vertexBuffer;
  20795. data[kind] = vbs[kind].getData();
  20796. newdata[kind] = [];
  20797. }
  20798. // Save previous submeshes
  20799. var previousSubmeshes = this.subMeshes.slice(0);
  20800. var indices = this.getIndices();
  20801. var totalIndices = this.getTotalIndices();
  20802. // Generating unique vertices per face
  20803. var index;
  20804. for (index = 0; index < totalIndices; index++) {
  20805. var vertexIndex = indices[index];
  20806. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20807. kind = kinds[kindIndex];
  20808. var stride = vbs[kind].getStrideSize();
  20809. for (var offset = 0; offset < stride; offset++) {
  20810. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20811. }
  20812. }
  20813. }
  20814. // Updating faces & normal
  20815. var normals = [];
  20816. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20817. for (index = 0; index < totalIndices; index += 3) {
  20818. indices[index] = index;
  20819. indices[index + 1] = index + 1;
  20820. indices[index + 2] = index + 2;
  20821. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20822. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20823. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20824. var p1p2 = p1.subtract(p2);
  20825. var p3p2 = p3.subtract(p2);
  20826. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20827. // Store same normals for every vertex
  20828. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20829. normals.push(normal.x);
  20830. normals.push(normal.y);
  20831. normals.push(normal.z);
  20832. }
  20833. }
  20834. this.setIndices(indices);
  20835. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20836. // Updating vertex buffers
  20837. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20838. kind = kinds[kindIndex];
  20839. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20840. }
  20841. // Updating submeshes
  20842. this.releaseSubMeshes();
  20843. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20844. var previousOne = previousSubmeshes[submeshIndex];
  20845. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20846. }
  20847. this.synchronizeInstances();
  20848. return this;
  20849. };
  20850. /**
  20851. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20852. * In other words, more vertices, no more indices and a single bigger VBO.
  20853. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20854. * Returns the Mesh.
  20855. */
  20856. Mesh.prototype.convertToUnIndexedMesh = function () {
  20857. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20858. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20859. var kinds = this.getVerticesDataKinds();
  20860. var vbs = [];
  20861. var data = [];
  20862. var newdata = [];
  20863. var updatableNormals = false;
  20864. var kindIndex;
  20865. var kind;
  20866. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20867. kind = kinds[kindIndex];
  20868. var vertexBuffer = this.getVertexBuffer(kind);
  20869. vbs[kind] = vertexBuffer;
  20870. data[kind] = vbs[kind].getData();
  20871. newdata[kind] = [];
  20872. }
  20873. // Save previous submeshes
  20874. var previousSubmeshes = this.subMeshes.slice(0);
  20875. var indices = this.getIndices();
  20876. var totalIndices = this.getTotalIndices();
  20877. // Generating unique vertices per face
  20878. var index;
  20879. for (index = 0; index < totalIndices; index++) {
  20880. var vertexIndex = indices[index];
  20881. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20882. kind = kinds[kindIndex];
  20883. var stride = vbs[kind].getStrideSize();
  20884. for (var offset = 0; offset < stride; offset++) {
  20885. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20886. }
  20887. }
  20888. }
  20889. // Updating indices
  20890. for (index = 0; index < totalIndices; index += 3) {
  20891. indices[index] = index;
  20892. indices[index + 1] = index + 1;
  20893. indices[index + 2] = index + 2;
  20894. }
  20895. this.setIndices(indices);
  20896. // Updating vertex buffers
  20897. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20898. kind = kinds[kindIndex];
  20899. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20900. }
  20901. // Updating submeshes
  20902. this.releaseSubMeshes();
  20903. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20904. var previousOne = previousSubmeshes[submeshIndex];
  20905. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20906. }
  20907. this._unIndexed = true;
  20908. this.synchronizeInstances();
  20909. return this;
  20910. };
  20911. /**
  20912. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20913. * This method returns the Mesh.
  20914. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20915. */
  20916. Mesh.prototype.flipFaces = function (flipNormals) {
  20917. if (flipNormals === void 0) { flipNormals = false; }
  20918. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20919. var i;
  20920. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20921. for (i = 0; i < vertex_data.normals.length; i++) {
  20922. vertex_data.normals[i] *= -1;
  20923. }
  20924. }
  20925. var temp;
  20926. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20927. // reassign indices
  20928. temp = vertex_data.indices[i + 1];
  20929. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20930. vertex_data.indices[i + 2] = temp;
  20931. }
  20932. vertex_data.applyToMesh(this);
  20933. return this;
  20934. };
  20935. // Instances
  20936. /**
  20937. * Creates a new InstancedMesh object from the mesh model.
  20938. * An instance shares the same properties and the same material than its model.
  20939. * Only these properties of each instance can then be set individually :
  20940. * - position
  20941. * - rotation
  20942. * - rotationQuaternion
  20943. * - setPivotMatrix
  20944. * - scaling
  20945. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20946. * Warning : this method is not supported for Line mesh and LineSystem
  20947. */
  20948. Mesh.prototype.createInstance = function (name) {
  20949. return new BABYLON.InstancedMesh(name, this);
  20950. };
  20951. /**
  20952. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20953. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20954. * This method returns the Mesh.
  20955. */
  20956. Mesh.prototype.synchronizeInstances = function () {
  20957. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20958. var instance = this.instances[instanceIndex];
  20959. instance._syncSubMeshes();
  20960. }
  20961. return this;
  20962. };
  20963. /**
  20964. * Simplify the mesh according to the given array of settings.
  20965. * Function will return immediately and will simplify async. It returns the Mesh.
  20966. * @param settings a collection of simplification settings.
  20967. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20968. * @param type the type of simplification to run.
  20969. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20970. */
  20971. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20972. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20973. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20974. this.getScene().simplificationQueue.addTask({
  20975. settings: settings,
  20976. parallelProcessing: parallelProcessing,
  20977. mesh: this,
  20978. simplificationType: simplificationType,
  20979. successCallback: successCallback
  20980. });
  20981. return this;
  20982. };
  20983. /**
  20984. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20985. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20986. * This should be used together with the simplification to avoid disappearing triangles.
  20987. * Returns the Mesh.
  20988. * @param successCallback an optional success callback to be called after the optimization finished.
  20989. */
  20990. Mesh.prototype.optimizeIndices = function (successCallback) {
  20991. var _this = this;
  20992. var indices = this.getIndices();
  20993. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20994. var vectorPositions = [];
  20995. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20996. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20997. }
  20998. var dupes = [];
  20999. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21000. var realPos = vectorPositions.length - 1 - iteration;
  21001. var testedPosition = vectorPositions[realPos];
  21002. for (var j = 0; j < realPos; ++j) {
  21003. var againstPosition = vectorPositions[j];
  21004. if (testedPosition.equals(againstPosition)) {
  21005. dupes[realPos] = j;
  21006. break;
  21007. }
  21008. }
  21009. }, function () {
  21010. for (var i = 0; i < indices.length; ++i) {
  21011. indices[i] = dupes[indices[i]] || indices[i];
  21012. }
  21013. //indices are now reordered
  21014. var originalSubMeshes = _this.subMeshes.slice(0);
  21015. _this.setIndices(indices);
  21016. _this.subMeshes = originalSubMeshes;
  21017. if (successCallback) {
  21018. successCallback(_this);
  21019. }
  21020. });
  21021. return this;
  21022. };
  21023. Mesh.prototype.serialize = function (serializationObject) {
  21024. serializationObject.name = this.name;
  21025. serializationObject.id = this.id;
  21026. serializationObject.type = this.getClassName();
  21027. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21028. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21029. }
  21030. serializationObject.position = this.position.asArray();
  21031. if (this.rotationQuaternion) {
  21032. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21033. }
  21034. else if (this.rotation) {
  21035. serializationObject.rotation = this.rotation.asArray();
  21036. }
  21037. serializationObject.scaling = this.scaling.asArray();
  21038. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21039. serializationObject.isEnabled = this.isEnabled();
  21040. serializationObject.isVisible = this.isVisible;
  21041. serializationObject.infiniteDistance = this.infiniteDistance;
  21042. serializationObject.pickable = this.isPickable;
  21043. serializationObject.receiveShadows = this.receiveShadows;
  21044. serializationObject.billboardMode = this.billboardMode;
  21045. serializationObject.visibility = this.visibility;
  21046. serializationObject.checkCollisions = this.checkCollisions;
  21047. serializationObject.isBlocker = this.isBlocker;
  21048. // Parent
  21049. if (this.parent) {
  21050. serializationObject.parentId = this.parent.id;
  21051. }
  21052. // Geometry
  21053. var geometry = this._geometry;
  21054. if (geometry) {
  21055. var geometryId = geometry.id;
  21056. serializationObject.geometryId = geometryId;
  21057. // SubMeshes
  21058. serializationObject.subMeshes = [];
  21059. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21060. var subMesh = this.subMeshes[subIndex];
  21061. serializationObject.subMeshes.push({
  21062. materialIndex: subMesh.materialIndex,
  21063. verticesStart: subMesh.verticesStart,
  21064. verticesCount: subMesh.verticesCount,
  21065. indexStart: subMesh.indexStart,
  21066. indexCount: subMesh.indexCount
  21067. });
  21068. }
  21069. }
  21070. // Material
  21071. if (this.material) {
  21072. serializationObject.materialId = this.material.id;
  21073. }
  21074. else {
  21075. this.material = null;
  21076. }
  21077. // Morph targets
  21078. if (this.morphTargetManager) {
  21079. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21080. }
  21081. // Skeleton
  21082. if (this.skeleton) {
  21083. serializationObject.skeletonId = this.skeleton.id;
  21084. }
  21085. // Physics
  21086. //TODO implement correct serialization for physics impostors.
  21087. if (this.getPhysicsImpostor()) {
  21088. var impostor = this.getPhysicsImpostor();
  21089. serializationObject.physicsMass = impostor.getParam("mass");
  21090. serializationObject.physicsFriction = impostor.getParam("friction");
  21091. serializationObject.physicsRestitution = impostor.getParam("mass");
  21092. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21093. }
  21094. // Metadata
  21095. if (this.metadata) {
  21096. serializationObject.metadata = this.metadata;
  21097. }
  21098. // Instances
  21099. serializationObject.instances = [];
  21100. for (var index = 0; index < this.instances.length; index++) {
  21101. var instance = this.instances[index];
  21102. var serializationInstance = {
  21103. name: instance.name,
  21104. position: instance.position.asArray(),
  21105. scaling: instance.scaling.asArray()
  21106. };
  21107. if (instance.rotationQuaternion) {
  21108. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21109. }
  21110. else if (instance.rotation) {
  21111. serializationInstance.rotation = instance.rotation.asArray();
  21112. }
  21113. serializationObject.instances.push(serializationInstance);
  21114. // Animations
  21115. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21116. serializationInstance.ranges = instance.serializeAnimationRanges();
  21117. }
  21118. //
  21119. // Animations
  21120. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21121. serializationObject.ranges = this.serializeAnimationRanges();
  21122. // Layer mask
  21123. serializationObject.layerMask = this.layerMask;
  21124. // Alpha
  21125. serializationObject.alphaIndex = this.alphaIndex;
  21126. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21127. // Overlay
  21128. serializationObject.overlayAlpha = this.overlayAlpha;
  21129. serializationObject.overlayColor = this.overlayColor.asArray();
  21130. serializationObject.renderOverlay = this.renderOverlay;
  21131. // Fog
  21132. serializationObject.applyFog = this.applyFog;
  21133. // Action Manager
  21134. if (this.actionManager) {
  21135. serializationObject.actions = this.actionManager.serialize(this.name);
  21136. }
  21137. };
  21138. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21139. if (!this.geometry) {
  21140. return;
  21141. }
  21142. this._markSubMeshesAsAttributesDirty();
  21143. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21144. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21145. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21146. this.morphTargetManager = undefined;
  21147. return;
  21148. }
  21149. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21150. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21151. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21152. if (morphTarget.hasNormals) {
  21153. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21154. }
  21155. if (morphTarget.hasTangents) {
  21156. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21157. }
  21158. }
  21159. }
  21160. else {
  21161. var index = 0;
  21162. // Positions
  21163. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21164. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21165. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21166. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21167. }
  21168. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21169. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21170. }
  21171. index++;
  21172. }
  21173. }
  21174. };
  21175. // Statics
  21176. /**
  21177. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21178. * The parameter `parsedMesh` is the mesh to be copied.
  21179. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21180. */
  21181. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21182. var mesh;
  21183. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21184. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21185. }
  21186. else {
  21187. mesh = new Mesh(parsedMesh.name, scene);
  21188. }
  21189. mesh.id = parsedMesh.id;
  21190. if (BABYLON.Tags) {
  21191. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21192. }
  21193. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21194. if (parsedMesh.metadata !== undefined) {
  21195. mesh.metadata = parsedMesh.metadata;
  21196. }
  21197. if (parsedMesh.rotationQuaternion) {
  21198. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21199. }
  21200. else if (parsedMesh.rotation) {
  21201. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21202. }
  21203. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21204. if (parsedMesh.localMatrix) {
  21205. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21206. }
  21207. else if (parsedMesh.pivotMatrix) {
  21208. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21209. }
  21210. mesh.setEnabled(parsedMesh.isEnabled);
  21211. mesh.isVisible = parsedMesh.isVisible;
  21212. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21213. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21214. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21215. if (parsedMesh.applyFog !== undefined) {
  21216. mesh.applyFog = parsedMesh.applyFog;
  21217. }
  21218. if (parsedMesh.pickable !== undefined) {
  21219. mesh.isPickable = parsedMesh.pickable;
  21220. }
  21221. if (parsedMesh.alphaIndex !== undefined) {
  21222. mesh.alphaIndex = parsedMesh.alphaIndex;
  21223. }
  21224. mesh.receiveShadows = parsedMesh.receiveShadows;
  21225. mesh.billboardMode = parsedMesh.billboardMode;
  21226. if (parsedMesh.visibility !== undefined) {
  21227. mesh.visibility = parsedMesh.visibility;
  21228. }
  21229. mesh.checkCollisions = parsedMesh.checkCollisions;
  21230. if (parsedMesh.isBlocker !== undefined) {
  21231. mesh.isBlocker = parsedMesh.isBlocker;
  21232. }
  21233. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21234. // freezeWorldMatrix
  21235. if (parsedMesh.freezeWorldMatrix) {
  21236. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21237. }
  21238. // Parent
  21239. if (parsedMesh.parentId) {
  21240. mesh._waitingParentId = parsedMesh.parentId;
  21241. }
  21242. // Actions
  21243. if (parsedMesh.actions !== undefined) {
  21244. mesh._waitingActions = parsedMesh.actions;
  21245. }
  21246. // Overlay
  21247. if (parsedMesh.overlayAlpha !== undefined) {
  21248. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21249. }
  21250. if (parsedMesh.overlayColor !== undefined) {
  21251. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21252. }
  21253. if (parsedMesh.renderOverlay !== undefined) {
  21254. mesh.renderOverlay = parsedMesh.renderOverlay;
  21255. }
  21256. // Geometry
  21257. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21258. if (parsedMesh.delayLoadingFile) {
  21259. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21260. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21261. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21262. if (parsedMesh._binaryInfo) {
  21263. mesh._binaryInfo = parsedMesh._binaryInfo;
  21264. }
  21265. mesh._delayInfo = [];
  21266. if (parsedMesh.hasUVs) {
  21267. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21268. }
  21269. if (parsedMesh.hasUVs2) {
  21270. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21271. }
  21272. if (parsedMesh.hasUVs3) {
  21273. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21274. }
  21275. if (parsedMesh.hasUVs4) {
  21276. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21277. }
  21278. if (parsedMesh.hasUVs5) {
  21279. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21280. }
  21281. if (parsedMesh.hasUVs6) {
  21282. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21283. }
  21284. if (parsedMesh.hasColors) {
  21285. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21286. }
  21287. if (parsedMesh.hasMatricesIndices) {
  21288. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21289. }
  21290. if (parsedMesh.hasMatricesWeights) {
  21291. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21292. }
  21293. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21294. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21295. mesh._checkDelayState();
  21296. }
  21297. }
  21298. else {
  21299. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21300. }
  21301. // Material
  21302. if (parsedMesh.materialId) {
  21303. mesh.setMaterialByID(parsedMesh.materialId);
  21304. }
  21305. else {
  21306. mesh.material = null;
  21307. }
  21308. // Morph targets
  21309. if (parsedMesh.morphTargetManagerId > -1) {
  21310. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21311. }
  21312. // Skeleton
  21313. if (parsedMesh.skeletonId > -1) {
  21314. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21315. if (parsedMesh.numBoneInfluencers) {
  21316. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21317. }
  21318. }
  21319. // Animations
  21320. if (parsedMesh.animations) {
  21321. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21322. var parsedAnimation = parsedMesh.animations[animationIndex];
  21323. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21324. }
  21325. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21326. }
  21327. if (parsedMesh.autoAnimate) {
  21328. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21329. }
  21330. // Layer Mask
  21331. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21332. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21333. }
  21334. else {
  21335. mesh.layerMask = 0x0FFFFFFF;
  21336. }
  21337. // Physics
  21338. if (parsedMesh.physicsImpostor) {
  21339. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21340. mass: parsedMesh.physicsMass,
  21341. friction: parsedMesh.physicsFriction,
  21342. restitution: parsedMesh.physicsRestitution
  21343. }, scene);
  21344. }
  21345. // Instances
  21346. if (parsedMesh.instances) {
  21347. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21348. var parsedInstance = parsedMesh.instances[index];
  21349. var instance = mesh.createInstance(parsedInstance.name);
  21350. if (BABYLON.Tags) {
  21351. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21352. }
  21353. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21354. if (parsedInstance.parentId) {
  21355. instance._waitingParentId = parsedInstance.parentId;
  21356. }
  21357. if (parsedInstance.rotationQuaternion) {
  21358. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21359. }
  21360. else if (parsedInstance.rotation) {
  21361. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21362. }
  21363. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21364. instance.checkCollisions = mesh.checkCollisions;
  21365. if (parsedMesh.animations) {
  21366. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21367. parsedAnimation = parsedMesh.animations[animationIndex];
  21368. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21369. }
  21370. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21371. }
  21372. }
  21373. }
  21374. return mesh;
  21375. };
  21376. /**
  21377. * Creates a ribbon mesh.
  21378. * Please consider using the same method from the MeshBuilder class instead.
  21379. * 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.
  21380. *
  21381. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21382. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21383. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21384. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21385. * 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.
  21386. * 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.
  21387. * 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
  21388. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21389. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21391. */
  21392. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21393. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21394. pathArray: pathArray,
  21395. closeArray: closeArray,
  21396. closePath: closePath,
  21397. offset: offset,
  21398. updatable: updatable,
  21399. sideOrientation: sideOrientation,
  21400. instance: instance
  21401. }, scene);
  21402. };
  21403. /**
  21404. * Creates a plane polygonal mesh. By default, this is a disc.
  21405. * Please consider using the same method from the MeshBuilder class instead.
  21406. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21407. * 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.
  21408. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21409. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21411. */
  21412. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21413. var options = {
  21414. radius: radius,
  21415. tessellation: tessellation,
  21416. sideOrientation: sideOrientation,
  21417. updatable: updatable
  21418. };
  21419. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21420. };
  21421. /**
  21422. * Creates a box mesh.
  21423. * Please consider using the same method from the MeshBuilder class instead.
  21424. * The parameter `size` sets the size (float) of each box side (default 1).
  21425. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21426. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21427. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21428. */
  21429. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21430. var options = {
  21431. size: size,
  21432. sideOrientation: sideOrientation,
  21433. updatable: updatable
  21434. };
  21435. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21436. };
  21437. /**
  21438. * Creates a sphere mesh.
  21439. * Please consider using the same method from the MeshBuilder class instead.
  21440. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21441. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21442. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21443. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21445. */
  21446. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21447. var options = {
  21448. segments: segments,
  21449. diameterX: diameter,
  21450. diameterY: diameter,
  21451. diameterZ: diameter,
  21452. sideOrientation: sideOrientation,
  21453. updatable: updatable
  21454. };
  21455. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21456. };
  21457. /**
  21458. * Creates a cylinder or a cone mesh.
  21459. * Please consider using the same method from the MeshBuilder class instead.
  21460. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21461. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21462. * 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.
  21463. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21464. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21465. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21466. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21468. */
  21469. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21470. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21471. if (scene !== undefined) {
  21472. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21473. updatable = scene;
  21474. }
  21475. scene = subdivisions;
  21476. subdivisions = 1;
  21477. }
  21478. var options = {
  21479. height: height,
  21480. diameterTop: diameterTop,
  21481. diameterBottom: diameterBottom,
  21482. tessellation: tessellation,
  21483. subdivisions: subdivisions,
  21484. sideOrientation: sideOrientation,
  21485. updatable: updatable
  21486. };
  21487. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21488. };
  21489. // Torus (Code from SharpDX.org)
  21490. /**
  21491. * Creates a torus mesh.
  21492. * Please consider using the same method from the MeshBuilder class instead.
  21493. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21494. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21495. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21496. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21497. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21498. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21499. */
  21500. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21501. var options = {
  21502. diameter: diameter,
  21503. thickness: thickness,
  21504. tessellation: tessellation,
  21505. sideOrientation: sideOrientation,
  21506. updatable: updatable
  21507. };
  21508. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21509. };
  21510. /**
  21511. * Creates a torus knot mesh.
  21512. * Please consider using the same method from the MeshBuilder class instead.
  21513. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21514. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21515. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21516. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21518. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21520. */
  21521. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21522. var options = {
  21523. radius: radius,
  21524. tube: tube,
  21525. radialSegments: radialSegments,
  21526. tubularSegments: tubularSegments,
  21527. p: p,
  21528. q: q,
  21529. sideOrientation: sideOrientation,
  21530. updatable: updatable
  21531. };
  21532. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21533. };
  21534. /**
  21535. * Creates a line mesh.
  21536. * Please consider using the same method from the MeshBuilder class instead.
  21537. * 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.
  21538. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21539. * The parameter `points` is an array successive Vector3.
  21540. * 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
  21541. * When updating an instance, remember that only point positions can change, not the number of points.
  21542. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21543. */
  21544. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21545. var options = {
  21546. points: points,
  21547. updatable: updatable,
  21548. instance: instance
  21549. };
  21550. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21551. };
  21552. /**
  21553. * Creates a dashed line mesh.
  21554. * Please consider using the same method from the MeshBuilder class instead.
  21555. * 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.
  21556. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21557. * The parameter `points` is an array successive Vector3.
  21558. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21559. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21560. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21561. * 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
  21562. * When updating an instance, remember that only point positions can change, not the number of points.
  21563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21564. */
  21565. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21566. var options = {
  21567. points: points,
  21568. dashSize: dashSize,
  21569. gapSize: gapSize,
  21570. dashNb: dashNb,
  21571. updatable: updatable,
  21572. instance: instance
  21573. };
  21574. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21575. };
  21576. /**
  21577. * Creates a polygon mesh.
  21578. * Please consider using the same method from the MeshBuilder class instead.
  21579. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21580. * 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.
  21581. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21583. * Remember you can only change the shape positions, not their number when updating a polygon.
  21584. */
  21585. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21586. var options = {
  21587. shape: shape,
  21588. holes: holes,
  21589. updatable: updatable,
  21590. sideOrientation: sideOrientation
  21591. };
  21592. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21593. };
  21594. /**
  21595. * Creates an extruded polygon mesh, with depth in the Y direction.
  21596. * Please consider using the same method from the MeshBuilder class instead.
  21597. */
  21598. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21599. var options = {
  21600. shape: shape,
  21601. holes: holes,
  21602. depth: depth,
  21603. updatable: updatable,
  21604. sideOrientation: sideOrientation
  21605. };
  21606. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21607. };
  21608. /**
  21609. * Creates an extruded shape mesh.
  21610. * 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.
  21611. * Please consider using the same method from the MeshBuilder class instead.
  21612. *
  21613. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21614. * 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
  21615. * extruded along the Z axis.
  21616. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21617. * 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.
  21618. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21619. * 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
  21620. * 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
  21621. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21622. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21623. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21624. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21625. */
  21626. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21627. var options = {
  21628. shape: shape,
  21629. path: path,
  21630. scale: scale,
  21631. rotation: rotation,
  21632. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21633. sideOrientation: sideOrientation,
  21634. instance: instance,
  21635. updatable: updatable
  21636. };
  21637. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21638. };
  21639. /**
  21640. * Creates an custom extruded shape mesh.
  21641. * 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.
  21642. * Please consider using the same method from the MeshBuilder class instead.
  21643. *
  21644. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21645. * 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
  21646. * extruded along the Z axis.
  21647. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21648. * 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
  21649. * and the distance of this point from the begining of the path :
  21650. * ```javascript
  21651. * var rotationFunction = function(i, distance) {
  21652. * // do things
  21653. * return rotationValue; }
  21654. * ```
  21655. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21656. * 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
  21657. * and the distance of this point from the begining of the path :
  21658. * ```javascript
  21659. * var scaleFunction = function(i, distance) {
  21660. * // do things
  21661. * return scaleValue;}
  21662. * ```
  21663. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21664. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21665. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21666. * 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
  21667. * 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
  21668. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21669. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21670. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21671. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21672. */
  21673. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21674. var options = {
  21675. shape: shape,
  21676. path: path,
  21677. scaleFunction: scaleFunction,
  21678. rotationFunction: rotationFunction,
  21679. ribbonCloseArray: ribbonCloseArray,
  21680. ribbonClosePath: ribbonClosePath,
  21681. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21682. sideOrientation: sideOrientation,
  21683. instance: instance,
  21684. updatable: updatable
  21685. };
  21686. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21687. };
  21688. /**
  21689. * Creates lathe mesh.
  21690. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21691. * Please consider using the same method from the MeshBuilder class instead.
  21692. * 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
  21693. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21694. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21695. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21696. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21697. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21698. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21699. */
  21700. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21701. var options = {
  21702. shape: shape,
  21703. radius: radius,
  21704. tessellation: tessellation,
  21705. sideOrientation: sideOrientation,
  21706. updatable: updatable
  21707. };
  21708. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21709. };
  21710. /**
  21711. * Creates a plane mesh.
  21712. * Please consider using the same method from the MeshBuilder class instead.
  21713. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21714. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21715. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21716. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21717. */
  21718. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21719. var options = {
  21720. size: size,
  21721. width: size,
  21722. height: size,
  21723. sideOrientation: sideOrientation,
  21724. updatable: updatable
  21725. };
  21726. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21727. };
  21728. /**
  21729. * Creates a ground mesh.
  21730. * Please consider using the same method from the MeshBuilder class instead.
  21731. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21732. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21733. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21734. */
  21735. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21736. var options = {
  21737. width: width,
  21738. height: height,
  21739. subdivisions: subdivisions,
  21740. updatable: updatable
  21741. };
  21742. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21743. };
  21744. /**
  21745. * Creates a tiled ground mesh.
  21746. * Please consider using the same method from the MeshBuilder class instead.
  21747. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21748. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21749. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21750. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21751. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21752. * numbers of subdivisions on the ground width and height of each tile.
  21753. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21754. */
  21755. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21756. var options = {
  21757. xmin: xmin,
  21758. zmin: zmin,
  21759. xmax: xmax,
  21760. zmax: zmax,
  21761. subdivisions: subdivisions,
  21762. precision: precision,
  21763. updatable: updatable
  21764. };
  21765. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21766. };
  21767. /**
  21768. * Creates a ground mesh from a height map.
  21769. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21770. * Please consider using the same method from the MeshBuilder class instead.
  21771. * The parameter `url` sets the URL of the height map image resource.
  21772. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21773. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21774. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21775. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21776. * 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).
  21777. * This function is passed the newly built mesh :
  21778. * ```javascript
  21779. * function(mesh) { // do things
  21780. * return; }
  21781. * ```
  21782. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21783. */
  21784. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21785. var options = {
  21786. width: width,
  21787. height: height,
  21788. subdivisions: subdivisions,
  21789. minHeight: minHeight,
  21790. maxHeight: maxHeight,
  21791. updatable: updatable,
  21792. onReady: onReady
  21793. };
  21794. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21795. };
  21796. /**
  21797. * Creates a tube mesh.
  21798. * 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.
  21799. * Please consider using the same method from the MeshBuilder class instead.
  21800. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21801. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21802. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21803. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21804. * 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.
  21805. * It must return a radius value (positive float) :
  21806. * ```javascript
  21807. * var radiusFunction = function(i, distance) {
  21808. * // do things
  21809. * return radius; }
  21810. * ```
  21811. * 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
  21812. * 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
  21813. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21814. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21815. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21816. */
  21817. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21818. var options = {
  21819. path: path,
  21820. radius: radius,
  21821. tessellation: tessellation,
  21822. radiusFunction: radiusFunction,
  21823. arc: 1,
  21824. cap: cap,
  21825. updatable: updatable,
  21826. sideOrientation: sideOrientation,
  21827. instance: instance
  21828. };
  21829. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21830. };
  21831. /**
  21832. * Creates a polyhedron mesh.
  21833. * Please consider using the same method from the MeshBuilder class instead.
  21834. * 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
  21835. * to choose the wanted type.
  21836. * The parameter `size` (positive float, default 1) sets the polygon size.
  21837. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21838. * 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`.
  21839. * 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
  21840. * 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)`).
  21841. * 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
  21842. * 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.
  21843. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21844. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21846. */
  21847. Mesh.CreatePolyhedron = function (name, options, scene) {
  21848. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21849. };
  21850. /**
  21851. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21852. * Please consider using the same method from the MeshBuilder class instead.
  21853. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21854. * 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`).
  21855. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21856. * 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.
  21857. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21858. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21859. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21860. */
  21861. Mesh.CreateIcoSphere = function (name, options, scene) {
  21862. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21863. };
  21864. /**
  21865. * Creates a decal mesh.
  21866. * Please consider using the same method from the MeshBuilder class instead.
  21867. * 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.
  21868. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21869. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21870. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21871. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21872. */
  21873. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21874. var options = {
  21875. position: position,
  21876. normal: normal,
  21877. size: size,
  21878. angle: angle
  21879. };
  21880. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21881. };
  21882. // Skeletons
  21883. /**
  21884. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21885. */
  21886. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21887. var source;
  21888. if (!this._sourcePositions) {
  21889. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21890. this._sourcePositions = new Float32Array(source);
  21891. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21892. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21893. }
  21894. }
  21895. return this._sourcePositions;
  21896. };
  21897. /**
  21898. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21899. */
  21900. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21901. var source;
  21902. if (!this._sourceNormals) {
  21903. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21904. this._sourceNormals = new Float32Array(source);
  21905. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21906. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21907. }
  21908. }
  21909. return this._sourceNormals;
  21910. };
  21911. /**
  21912. * Updates the vertex buffer by applying transformation from the bones.
  21913. * Returns the Mesh.
  21914. *
  21915. * @param {skeleton} skeleton to apply
  21916. */
  21917. Mesh.prototype.applySkeleton = function (skeleton) {
  21918. if (!this.geometry) {
  21919. return this;
  21920. }
  21921. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21922. return this;
  21923. }
  21924. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21925. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21926. return this;
  21927. }
  21928. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21929. return this;
  21930. }
  21931. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21932. return this;
  21933. }
  21934. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21935. return this;
  21936. }
  21937. if (!this._sourcePositions) {
  21938. var submeshes = this.subMeshes.slice();
  21939. this.setPositionsForCPUSkinning();
  21940. this.subMeshes = submeshes;
  21941. }
  21942. if (!this._sourceNormals) {
  21943. this.setNormalsForCPUSkinning();
  21944. }
  21945. // positionsData checks for not being Float32Array will only pass at most once
  21946. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21947. if (!(positionsData instanceof Float32Array)) {
  21948. positionsData = new Float32Array(positionsData);
  21949. }
  21950. // normalsData checks for not being Float32Array will only pass at most once
  21951. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21952. if (!(normalsData instanceof Float32Array)) {
  21953. normalsData = new Float32Array(normalsData);
  21954. }
  21955. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21956. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21957. var needExtras = this.numBoneInfluencers > 4;
  21958. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21959. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21960. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21961. var tempVector3 = BABYLON.Vector3.Zero();
  21962. var finalMatrix = new BABYLON.Matrix();
  21963. var tempMatrix = new BABYLON.Matrix();
  21964. var matWeightIdx = 0;
  21965. var inf;
  21966. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21967. var weight;
  21968. for (inf = 0; inf < 4; inf++) {
  21969. weight = matricesWeightsData[matWeightIdx + inf];
  21970. if (weight > 0) {
  21971. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21972. finalMatrix.addToSelf(tempMatrix);
  21973. }
  21974. else
  21975. break;
  21976. }
  21977. if (needExtras) {
  21978. for (inf = 0; inf < 4; inf++) {
  21979. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21980. if (weight > 0) {
  21981. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21982. finalMatrix.addToSelf(tempMatrix);
  21983. }
  21984. else
  21985. break;
  21986. }
  21987. }
  21988. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21989. tempVector3.toArray(positionsData, index);
  21990. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21991. tempVector3.toArray(normalsData, index);
  21992. finalMatrix.reset();
  21993. }
  21994. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21995. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21996. return this;
  21997. };
  21998. // Tools
  21999. /**
  22000. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22001. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22002. */
  22003. Mesh.MinMax = function (meshes) {
  22004. var minVector = null;
  22005. var maxVector = null;
  22006. meshes.forEach(function (mesh, index, array) {
  22007. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22008. if (!minVector) {
  22009. minVector = boundingBox.minimumWorld;
  22010. maxVector = boundingBox.maximumWorld;
  22011. }
  22012. else {
  22013. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22014. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22015. }
  22016. });
  22017. return {
  22018. min: minVector,
  22019. max: maxVector
  22020. };
  22021. };
  22022. /**
  22023. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22024. */
  22025. Mesh.Center = function (meshesOrMinMaxVector) {
  22026. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22027. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22028. };
  22029. /**
  22030. * Merge the array of meshes into a single mesh for performance reasons.
  22031. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22032. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22033. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22034. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22035. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22036. */
  22037. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22038. if (disposeSource === void 0) { disposeSource = true; }
  22039. var index;
  22040. if (!allow32BitsIndices) {
  22041. var totalVertices = 0;
  22042. // Counting vertices
  22043. for (index = 0; index < meshes.length; index++) {
  22044. if (meshes[index]) {
  22045. totalVertices += meshes[index].getTotalVertices();
  22046. if (totalVertices > 65536) {
  22047. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22048. return null;
  22049. }
  22050. }
  22051. }
  22052. }
  22053. // Merge
  22054. var vertexData;
  22055. var otherVertexData;
  22056. var indiceArray = new Array();
  22057. var source;
  22058. for (index = 0; index < meshes.length; index++) {
  22059. if (meshes[index]) {
  22060. meshes[index].computeWorldMatrix(true);
  22061. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22062. otherVertexData.transform(meshes[index].getWorldMatrix());
  22063. if (vertexData) {
  22064. vertexData.merge(otherVertexData);
  22065. }
  22066. else {
  22067. vertexData = otherVertexData;
  22068. source = meshes[index];
  22069. }
  22070. if (subdivideWithSubMeshes) {
  22071. indiceArray.push(meshes[index].getTotalIndices());
  22072. }
  22073. }
  22074. }
  22075. if (!meshSubclass) {
  22076. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22077. }
  22078. vertexData.applyToMesh(meshSubclass);
  22079. // Setting properties
  22080. meshSubclass.material = source.material;
  22081. meshSubclass.checkCollisions = source.checkCollisions;
  22082. // Cleaning
  22083. if (disposeSource) {
  22084. for (index = 0; index < meshes.length; index++) {
  22085. if (meshes[index]) {
  22086. meshes[index].dispose();
  22087. }
  22088. }
  22089. }
  22090. // Subdivide
  22091. if (subdivideWithSubMeshes) {
  22092. //-- Suppresions du submesh global
  22093. meshSubclass.releaseSubMeshes();
  22094. index = 0;
  22095. var offset = 0;
  22096. //-- aplique la subdivision en fonction du tableau d'indices
  22097. while (index < indiceArray.length) {
  22098. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22099. offset += indiceArray[index];
  22100. index++;
  22101. }
  22102. }
  22103. return meshSubclass;
  22104. };
  22105. return Mesh;
  22106. }(BABYLON.AbstractMesh));
  22107. // Consts
  22108. Mesh._FRONTSIDE = 0;
  22109. Mesh._BACKSIDE = 1;
  22110. Mesh._DOUBLESIDE = 2;
  22111. Mesh._DEFAULTSIDE = 0;
  22112. Mesh._NO_CAP = 0;
  22113. Mesh._CAP_START = 1;
  22114. Mesh._CAP_END = 2;
  22115. Mesh._CAP_ALL = 3;
  22116. BABYLON.Mesh = Mesh;
  22117. })(BABYLON || (BABYLON = {}));
  22118. //# sourceMappingURL=babylon.mesh.js.map
  22119. var BABYLON;
  22120. (function (BABYLON) {
  22121. var SubMesh = (function () {
  22122. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22123. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22124. this.materialIndex = materialIndex;
  22125. this.verticesStart = verticesStart;
  22126. this.verticesCount = verticesCount;
  22127. this.indexStart = indexStart;
  22128. this.indexCount = indexCount;
  22129. this._renderId = 0;
  22130. this._mesh = mesh;
  22131. this._renderingMesh = renderingMesh || mesh;
  22132. mesh.subMeshes.push(this);
  22133. this._trianglePlanes = [];
  22134. this._id = mesh.subMeshes.length - 1;
  22135. if (createBoundingBox) {
  22136. this.refreshBoundingInfo();
  22137. mesh.computeWorldMatrix(true);
  22138. }
  22139. }
  22140. Object.defineProperty(SubMesh.prototype, "effect", {
  22141. get: function () {
  22142. return this._materialEffect;
  22143. },
  22144. enumerable: true,
  22145. configurable: true
  22146. });
  22147. SubMesh.prototype.setEffect = function (effect, defines) {
  22148. if (this._materialEffect === effect) {
  22149. return;
  22150. }
  22151. this._materialDefines = defines;
  22152. this._materialEffect = effect;
  22153. };
  22154. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22155. get: function () {
  22156. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22157. },
  22158. enumerable: true,
  22159. configurable: true
  22160. });
  22161. /**
  22162. * Returns the submesh BoudingInfo object.
  22163. */
  22164. SubMesh.prototype.getBoundingInfo = function () {
  22165. if (this.IsGlobal) {
  22166. return this._mesh.getBoundingInfo();
  22167. }
  22168. return this._boundingInfo;
  22169. };
  22170. /**
  22171. * Sets the submesh BoundingInfo.
  22172. * Return the SubMesh.
  22173. */
  22174. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22175. this._boundingInfo = boundingInfo;
  22176. return this;
  22177. };
  22178. /**
  22179. * Returns the mesh of the current submesh.
  22180. */
  22181. SubMesh.prototype.getMesh = function () {
  22182. return this._mesh;
  22183. };
  22184. /**
  22185. * Returns the rendering mesh of the submesh.
  22186. */
  22187. SubMesh.prototype.getRenderingMesh = function () {
  22188. return this._renderingMesh;
  22189. };
  22190. /**
  22191. * Returns the submesh material.
  22192. */
  22193. SubMesh.prototype.getMaterial = function () {
  22194. var rootMaterial = this._renderingMesh.material;
  22195. if (rootMaterial && rootMaterial.getSubMaterial) {
  22196. var multiMaterial = rootMaterial;
  22197. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22198. if (this._currentMaterial !== effectiveMaterial) {
  22199. this._currentMaterial = effectiveMaterial;
  22200. if (this._materialDefines) {
  22201. this._materialDefines.markAllAsDirty();
  22202. }
  22203. }
  22204. return effectiveMaterial;
  22205. }
  22206. if (!rootMaterial) {
  22207. return this._mesh.getScene().defaultMaterial;
  22208. }
  22209. return rootMaterial;
  22210. };
  22211. // Methods
  22212. /**
  22213. * Sets a new updated BoundingInfo object to the submesh.
  22214. * Returns the SubMesh.
  22215. */
  22216. SubMesh.prototype.refreshBoundingInfo = function () {
  22217. this._lastColliderWorldVertices = null;
  22218. if (this.IsGlobal) {
  22219. return;
  22220. }
  22221. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22222. if (!data) {
  22223. this._boundingInfo = this._mesh._boundingInfo;
  22224. return;
  22225. }
  22226. var indices = this._renderingMesh.getIndices();
  22227. var extend;
  22228. //is this the only submesh?
  22229. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22230. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22231. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22232. }
  22233. else {
  22234. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22235. }
  22236. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22237. return this;
  22238. };
  22239. SubMesh.prototype._checkCollision = function (collider) {
  22240. return this.getBoundingInfo()._checkCollision(collider);
  22241. };
  22242. /**
  22243. * Updates the submesh BoundingInfo.
  22244. * Returns the Submesh.
  22245. */
  22246. SubMesh.prototype.updateBoundingInfo = function (world) {
  22247. if (!this.getBoundingInfo()) {
  22248. this.refreshBoundingInfo();
  22249. }
  22250. this.getBoundingInfo().update(world);
  22251. return this;
  22252. };
  22253. /**
  22254. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22255. * Boolean returned.
  22256. */
  22257. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22258. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22259. };
  22260. /**
  22261. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22262. * Boolean returned.
  22263. */
  22264. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22265. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22266. };
  22267. /**
  22268. * Renders the submesh.
  22269. * Returns it.
  22270. */
  22271. SubMesh.prototype.render = function (enableAlphaMode) {
  22272. this._renderingMesh.render(this, enableAlphaMode);
  22273. return this;
  22274. };
  22275. /**
  22276. * Returns a new Index Buffer.
  22277. * Type returned : WebGLBuffer.
  22278. */
  22279. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22280. if (!this._linesIndexBuffer) {
  22281. var linesIndices = [];
  22282. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22283. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22284. }
  22285. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22286. this.linesIndexCount = linesIndices.length;
  22287. }
  22288. return this._linesIndexBuffer;
  22289. };
  22290. /**
  22291. * True is the passed Ray intersects the submesh bounding box.
  22292. * Boolean returned.
  22293. */
  22294. SubMesh.prototype.canIntersects = function (ray) {
  22295. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22296. };
  22297. /**
  22298. * Returns an object IntersectionInfo.
  22299. */
  22300. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22301. var intersectInfo = null;
  22302. // LineMesh first as it's also a Mesh...
  22303. if (this._mesh instanceof BABYLON.LinesMesh) {
  22304. var lineMesh = this._mesh;
  22305. // Line test
  22306. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22307. var p0 = positions[indices[index]];
  22308. var p1 = positions[indices[index + 1]];
  22309. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22310. if (length < 0) {
  22311. continue;
  22312. }
  22313. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22314. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22315. if (fastCheck) {
  22316. break;
  22317. }
  22318. }
  22319. }
  22320. }
  22321. else {
  22322. // Triangles test
  22323. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22324. var p0 = positions[indices[index]];
  22325. var p1 = positions[indices[index + 1]];
  22326. var p2 = positions[indices[index + 2]];
  22327. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22328. if (currentIntersectInfo) {
  22329. if (currentIntersectInfo.distance < 0) {
  22330. continue;
  22331. }
  22332. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22333. intersectInfo = currentIntersectInfo;
  22334. intersectInfo.faceId = index / 3;
  22335. if (fastCheck) {
  22336. break;
  22337. }
  22338. }
  22339. }
  22340. }
  22341. }
  22342. return intersectInfo;
  22343. };
  22344. // Clone
  22345. /**
  22346. * Creates a new Submesh from the passed Mesh.
  22347. */
  22348. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22349. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22350. if (!this.IsGlobal) {
  22351. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22352. }
  22353. return result;
  22354. };
  22355. // Dispose
  22356. /**
  22357. * Disposes the Submesh.
  22358. * Returns nothing.
  22359. */
  22360. SubMesh.prototype.dispose = function () {
  22361. if (this._linesIndexBuffer) {
  22362. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22363. this._linesIndexBuffer = null;
  22364. }
  22365. // Remove from mesh
  22366. var index = this._mesh.subMeshes.indexOf(this);
  22367. this._mesh.subMeshes.splice(index, 1);
  22368. };
  22369. // Statics
  22370. /**
  22371. * Creates a new Submesh from the passed parameters :
  22372. * - materialIndex (integer) : the index of the main mesh material.
  22373. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22374. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22375. * - mesh (Mesh) : the main mesh to create the submesh from.
  22376. * - renderingMesh (optional Mesh) : rendering mesh.
  22377. */
  22378. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22379. var minVertexIndex = Number.MAX_VALUE;
  22380. var maxVertexIndex = -Number.MAX_VALUE;
  22381. renderingMesh = renderingMesh || mesh;
  22382. var indices = renderingMesh.getIndices();
  22383. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22384. var vertexIndex = indices[index];
  22385. if (vertexIndex < minVertexIndex)
  22386. minVertexIndex = vertexIndex;
  22387. if (vertexIndex > maxVertexIndex)
  22388. maxVertexIndex = vertexIndex;
  22389. }
  22390. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22391. };
  22392. return SubMesh;
  22393. }());
  22394. BABYLON.SubMesh = SubMesh;
  22395. })(BABYLON || (BABYLON = {}));
  22396. //# sourceMappingURL=babylon.subMesh.js.map
  22397. var BABYLON;
  22398. (function (BABYLON) {
  22399. var EffectFallbacks = (function () {
  22400. function EffectFallbacks() {
  22401. this._defines = {};
  22402. this._currentRank = 32;
  22403. this._maxRank = -1;
  22404. }
  22405. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22406. if (!this._defines[rank]) {
  22407. if (rank < this._currentRank) {
  22408. this._currentRank = rank;
  22409. }
  22410. if (rank > this._maxRank) {
  22411. this._maxRank = rank;
  22412. }
  22413. this._defines[rank] = new Array();
  22414. }
  22415. this._defines[rank].push(define);
  22416. };
  22417. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22418. this._meshRank = rank;
  22419. this._mesh = mesh;
  22420. if (rank < this._currentRank) {
  22421. this._currentRank = rank;
  22422. }
  22423. if (rank > this._maxRank) {
  22424. this._maxRank = rank;
  22425. }
  22426. };
  22427. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22428. get: function () {
  22429. return this._currentRank <= this._maxRank;
  22430. },
  22431. enumerable: true,
  22432. configurable: true
  22433. });
  22434. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22435. // First we try to switch to CPU skinning
  22436. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22437. this._mesh.computeBonesUsingShaders = false;
  22438. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22439. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22440. var scene = this._mesh.getScene();
  22441. for (var index = 0; index < scene.meshes.length; index++) {
  22442. var otherMesh = scene.meshes[index];
  22443. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22444. otherMesh.computeBonesUsingShaders = false;
  22445. }
  22446. }
  22447. }
  22448. else {
  22449. var currentFallbacks = this._defines[this._currentRank];
  22450. if (currentFallbacks) {
  22451. for (var index = 0; index < currentFallbacks.length; index++) {
  22452. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22453. }
  22454. }
  22455. this._currentRank++;
  22456. }
  22457. return currentDefines;
  22458. };
  22459. return EffectFallbacks;
  22460. }());
  22461. BABYLON.EffectFallbacks = EffectFallbacks;
  22462. var EffectCreationOptions = (function () {
  22463. function EffectCreationOptions() {
  22464. }
  22465. return EffectCreationOptions;
  22466. }());
  22467. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22468. var Effect = (function () {
  22469. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22470. var _this = this;
  22471. this.uniqueId = 0;
  22472. this._uniformBuffersNames = {};
  22473. this._isReady = false;
  22474. this._compilationError = "";
  22475. this._valueCache = {};
  22476. this.name = baseName;
  22477. if (attributesNamesOrOptions.attributes) {
  22478. var options = attributesNamesOrOptions;
  22479. this._engine = uniformsNamesOrEngine;
  22480. this._attributesNames = options.attributes;
  22481. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22482. this._samplers = options.samplers;
  22483. this.defines = options.defines;
  22484. this.onError = options.onError;
  22485. this.onCompiled = options.onCompiled;
  22486. this._fallbacks = options.fallbacks;
  22487. this._indexParameters = options.indexParameters;
  22488. if (options.uniformBuffersNames) {
  22489. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22490. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22491. }
  22492. }
  22493. }
  22494. else {
  22495. this._engine = engine;
  22496. this.defines = defines;
  22497. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22498. this._samplers = samplers;
  22499. this._attributesNames = attributesNamesOrOptions;
  22500. this.onError = onError;
  22501. this.onCompiled = onCompiled;
  22502. this._indexParameters = indexParameters;
  22503. this._fallbacks = fallbacks;
  22504. }
  22505. this.uniqueId = Effect._uniqueIdSeed++;
  22506. var vertexSource;
  22507. var fragmentSource;
  22508. if (baseName.vertexElement) {
  22509. vertexSource = document.getElementById(baseName.vertexElement);
  22510. if (!vertexSource) {
  22511. vertexSource = baseName.vertexElement;
  22512. }
  22513. }
  22514. else {
  22515. vertexSource = baseName.vertex || baseName;
  22516. }
  22517. if (baseName.fragmentElement) {
  22518. fragmentSource = document.getElementById(baseName.fragmentElement);
  22519. if (!fragmentSource) {
  22520. fragmentSource = baseName.fragmentElement;
  22521. }
  22522. }
  22523. else {
  22524. fragmentSource = baseName.fragment || baseName;
  22525. }
  22526. this._loadVertexShader(vertexSource, function (vertexCode) {
  22527. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22528. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22529. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22530. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22531. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22532. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22533. });
  22534. });
  22535. });
  22536. });
  22537. });
  22538. });
  22539. }
  22540. Object.defineProperty(Effect.prototype, "key", {
  22541. get: function () {
  22542. return this._key;
  22543. },
  22544. enumerable: true,
  22545. configurable: true
  22546. });
  22547. // Properties
  22548. Effect.prototype.isReady = function () {
  22549. return this._isReady;
  22550. };
  22551. Effect.prototype.getProgram = function () {
  22552. return this._program;
  22553. };
  22554. Effect.prototype.getAttributesNames = function () {
  22555. return this._attributesNames;
  22556. };
  22557. Effect.prototype.getAttributeLocation = function (index) {
  22558. return this._attributes[index];
  22559. };
  22560. Effect.prototype.getAttributeLocationByName = function (name) {
  22561. var index = this._attributesNames.indexOf(name);
  22562. return this._attributes[index];
  22563. };
  22564. Effect.prototype.getAttributesCount = function () {
  22565. return this._attributes.length;
  22566. };
  22567. Effect.prototype.getUniformIndex = function (uniformName) {
  22568. return this._uniformsNames.indexOf(uniformName);
  22569. };
  22570. Effect.prototype.getUniform = function (uniformName) {
  22571. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22572. };
  22573. Effect.prototype.getSamplers = function () {
  22574. return this._samplers;
  22575. };
  22576. Effect.prototype.getCompilationError = function () {
  22577. return this._compilationError;
  22578. };
  22579. Effect.prototype.getVertexShaderSource = function () {
  22580. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22581. };
  22582. Effect.prototype.getFragmentShaderSource = function () {
  22583. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22584. };
  22585. // Methods
  22586. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22587. // DOM element ?
  22588. if (vertex instanceof HTMLElement) {
  22589. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22590. callback(vertexCode);
  22591. return;
  22592. }
  22593. // Base64 encoded ?
  22594. if (vertex.substr(0, 7) === "base64:") {
  22595. var vertexBinary = window.atob(vertex.substr(7));
  22596. callback(vertexBinary);
  22597. return;
  22598. }
  22599. // Is in local store ?
  22600. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22601. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22602. return;
  22603. }
  22604. var vertexShaderUrl;
  22605. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22606. vertexShaderUrl = vertex;
  22607. }
  22608. else {
  22609. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22610. }
  22611. // Vertex shader
  22612. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22613. };
  22614. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22615. // DOM element ?
  22616. if (fragment instanceof HTMLElement) {
  22617. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22618. callback(fragmentCode);
  22619. return;
  22620. }
  22621. // Base64 encoded ?
  22622. if (fragment.substr(0, 7) === "base64:") {
  22623. var fragmentBinary = window.atob(fragment.substr(7));
  22624. callback(fragmentBinary);
  22625. return;
  22626. }
  22627. // Is in local store ?
  22628. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22629. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22630. return;
  22631. }
  22632. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22633. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22634. return;
  22635. }
  22636. var fragmentShaderUrl;
  22637. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22638. fragmentShaderUrl = fragment;
  22639. }
  22640. else {
  22641. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22642. }
  22643. // Fragment shader
  22644. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22645. };
  22646. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22647. // Rebuild shaders source code
  22648. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22649. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22650. vertexCode = prefix + vertexCode;
  22651. fragmentCode = prefix + fragmentCode;
  22652. // Number lines of shaders source code
  22653. var i = 2;
  22654. var regex = /\n/gm;
  22655. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22656. i = 2;
  22657. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22658. // Dump shaders name and formatted source code
  22659. if (this.name.vertexElement) {
  22660. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22661. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22662. }
  22663. else if (this.name.vertex) {
  22664. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22665. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22666. }
  22667. else {
  22668. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22669. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22670. }
  22671. };
  22672. ;
  22673. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22674. var preparedSourceCode = this._processPrecision(sourceCode);
  22675. if (this._engine.webGLVersion == 1) {
  22676. callback(preparedSourceCode);
  22677. return;
  22678. }
  22679. // Already converted
  22680. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22681. callback(preparedSourceCode.replace("#version 300 es", ""));
  22682. return;
  22683. }
  22684. // Remove extensions
  22685. // #extension GL_OES_standard_derivatives : enable
  22686. // #extension GL_EXT_shader_texture_lod : enable
  22687. // #extension GL_EXT_frag_depth : enable
  22688. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22689. var result = preparedSourceCode.replace(regex, "");
  22690. // Migrate to GLSL v300
  22691. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22692. result = result.replace(/attribute[ \t]/g, "in ");
  22693. result = result.replace(/[ \t]attribute/g, " in");
  22694. if (isFragment) {
  22695. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22696. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22697. result = result.replace(/texture2D\(/g, "texture(");
  22698. result = result.replace(/textureCube\(/g, "texture(");
  22699. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22700. result = result.replace(/gl_FragColor/g, "glFragColor");
  22701. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22702. }
  22703. callback(result);
  22704. };
  22705. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22706. var _this = this;
  22707. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22708. var match = regex.exec(sourceCode);
  22709. var returnValue = new String(sourceCode);
  22710. while (match != null) {
  22711. var includeFile = match[1];
  22712. // Uniform declaration
  22713. if (includeFile.indexOf("__decl__") !== -1) {
  22714. includeFile = includeFile.replace(/__decl__/, "");
  22715. if (this._engine.webGLVersion != 1) {
  22716. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22717. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22718. }
  22719. includeFile = includeFile + "Declaration";
  22720. }
  22721. if (Effect.IncludesShadersStore[includeFile]) {
  22722. // Substitution
  22723. var includeContent = Effect.IncludesShadersStore[includeFile];
  22724. if (match[2]) {
  22725. var splits = match[3].split(",");
  22726. for (var index = 0; index < splits.length; index += 2) {
  22727. var source = new RegExp(splits[index], "g");
  22728. var dest = splits[index + 1];
  22729. includeContent = includeContent.replace(source, dest);
  22730. }
  22731. }
  22732. if (match[4]) {
  22733. var indexString = match[5];
  22734. if (indexString.indexOf("..") !== -1) {
  22735. var indexSplits = indexString.split("..");
  22736. var minIndex = parseInt(indexSplits[0]);
  22737. var maxIndex = parseInt(indexSplits[1]);
  22738. var sourceIncludeContent = includeContent.slice(0);
  22739. includeContent = "";
  22740. if (isNaN(maxIndex)) {
  22741. maxIndex = this._indexParameters[indexSplits[1]];
  22742. }
  22743. for (var i = minIndex; i < maxIndex; i++) {
  22744. if (this._engine.webGLVersion === 1) {
  22745. // Ubo replacement
  22746. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22747. return p1 + "{X}";
  22748. });
  22749. }
  22750. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22751. }
  22752. }
  22753. else {
  22754. if (this._engine.webGLVersion === 1) {
  22755. // Ubo replacement
  22756. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22757. return p1 + "{X}";
  22758. });
  22759. }
  22760. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22761. }
  22762. }
  22763. // Replace
  22764. returnValue = returnValue.replace(match[0], includeContent);
  22765. }
  22766. else {
  22767. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22768. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22769. Effect.IncludesShadersStore[includeFile] = fileContent;
  22770. _this._processIncludes(returnValue, callback);
  22771. });
  22772. return;
  22773. }
  22774. match = regex.exec(sourceCode);
  22775. }
  22776. callback(returnValue);
  22777. };
  22778. Effect.prototype._processPrecision = function (source) {
  22779. if (source.indexOf("precision highp float") === -1) {
  22780. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22781. source = "precision mediump float;\n" + source;
  22782. }
  22783. else {
  22784. source = "precision highp float;\n" + source;
  22785. }
  22786. }
  22787. else {
  22788. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22789. source = source.replace("precision highp float", "precision mediump float");
  22790. }
  22791. }
  22792. return source;
  22793. };
  22794. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22795. try {
  22796. var engine = this._engine;
  22797. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22798. if (engine.webGLVersion > 1) {
  22799. for (var name in this._uniformBuffersNames) {
  22800. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  22801. }
  22802. }
  22803. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22804. this._attributes = engine.getAttributes(this._program, attributesNames);
  22805. var index;
  22806. for (index = 0; index < this._samplers.length; index++) {
  22807. var sampler = this.getUniform(this._samplers[index]);
  22808. if (sampler == null) {
  22809. this._samplers.splice(index, 1);
  22810. index--;
  22811. }
  22812. }
  22813. engine.bindSamplers(this);
  22814. this._compilationError = "";
  22815. this._isReady = true;
  22816. if (this.onCompiled) {
  22817. this.onCompiled(this);
  22818. }
  22819. }
  22820. catch (e) {
  22821. this._compilationError = e.message;
  22822. // Let's go through fallbacks then
  22823. BABYLON.Tools.Error("Unable to compile effect:");
  22824. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  22825. return " " + uniform;
  22826. }));
  22827. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  22828. return " " + attribute;
  22829. }));
  22830. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  22831. BABYLON.Tools.Error("Error: " + this._compilationError);
  22832. if (fallbacks && fallbacks.isMoreFallbacks) {
  22833. BABYLON.Tools.Error("Trying next fallback.");
  22834. defines = fallbacks.reduce(defines);
  22835. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22836. }
  22837. else {
  22838. if (this.onError) {
  22839. this.onError(this, this._compilationError);
  22840. }
  22841. }
  22842. }
  22843. };
  22844. Object.defineProperty(Effect.prototype, "isSupported", {
  22845. get: function () {
  22846. return this._compilationError === "";
  22847. },
  22848. enumerable: true,
  22849. configurable: true
  22850. });
  22851. Effect.prototype._bindTexture = function (channel, texture) {
  22852. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22853. };
  22854. Effect.prototype.setTexture = function (channel, texture) {
  22855. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  22856. };
  22857. Effect.prototype.setTextureArray = function (channel, textures) {
  22858. if (this._samplers.indexOf(channel + "Ex") === -1) {
  22859. var initialPos = this._samplers.indexOf(channel);
  22860. for (var index = 1; index < textures.length; index++) {
  22861. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  22862. }
  22863. }
  22864. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  22865. };
  22866. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22867. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22868. };
  22869. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22870. var cache = this._valueCache[uniformName];
  22871. var flag = matrix.updateFlag;
  22872. if (cache !== undefined && cache === flag) {
  22873. return false;
  22874. }
  22875. this._valueCache[uniformName] = flag;
  22876. return true;
  22877. };
  22878. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22879. var cache = this._valueCache[uniformName];
  22880. if (!cache) {
  22881. cache = [x, y];
  22882. this._valueCache[uniformName] = cache;
  22883. return true;
  22884. }
  22885. var changed = false;
  22886. if (cache[0] !== x) {
  22887. cache[0] = x;
  22888. changed = true;
  22889. }
  22890. if (cache[1] !== y) {
  22891. cache[1] = y;
  22892. changed = true;
  22893. }
  22894. return changed;
  22895. };
  22896. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22897. var cache = this._valueCache[uniformName];
  22898. if (!cache) {
  22899. cache = [x, y, z];
  22900. this._valueCache[uniformName] = cache;
  22901. return true;
  22902. }
  22903. var changed = false;
  22904. if (cache[0] !== x) {
  22905. cache[0] = x;
  22906. changed = true;
  22907. }
  22908. if (cache[1] !== y) {
  22909. cache[1] = y;
  22910. changed = true;
  22911. }
  22912. if (cache[2] !== z) {
  22913. cache[2] = z;
  22914. changed = true;
  22915. }
  22916. return changed;
  22917. };
  22918. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22919. var cache = this._valueCache[uniformName];
  22920. if (!cache) {
  22921. cache = [x, y, z, w];
  22922. this._valueCache[uniformName] = cache;
  22923. return true;
  22924. }
  22925. var changed = false;
  22926. if (cache[0] !== x) {
  22927. cache[0] = x;
  22928. changed = true;
  22929. }
  22930. if (cache[1] !== y) {
  22931. cache[1] = y;
  22932. changed = true;
  22933. }
  22934. if (cache[2] !== z) {
  22935. cache[2] = z;
  22936. changed = true;
  22937. }
  22938. if (cache[3] !== w) {
  22939. cache[3] = w;
  22940. changed = true;
  22941. }
  22942. return changed;
  22943. };
  22944. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  22945. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  22946. return;
  22947. }
  22948. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  22949. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  22950. };
  22951. Effect.prototype.bindUniformBlock = function (blockName, index) {
  22952. this._engine.bindUniformBlock(this._program, blockName, index);
  22953. };
  22954. Effect.prototype.setIntArray = function (uniformName, array) {
  22955. this._valueCache[uniformName] = null;
  22956. this._engine.setIntArray(this.getUniform(uniformName), array);
  22957. return this;
  22958. };
  22959. Effect.prototype.setIntArray2 = function (uniformName, array) {
  22960. this._valueCache[uniformName] = null;
  22961. this._engine.setIntArray2(this.getUniform(uniformName), array);
  22962. return this;
  22963. };
  22964. Effect.prototype.setIntArray3 = function (uniformName, array) {
  22965. this._valueCache[uniformName] = null;
  22966. this._engine.setIntArray3(this.getUniform(uniformName), array);
  22967. return this;
  22968. };
  22969. Effect.prototype.setIntArray4 = function (uniformName, array) {
  22970. this._valueCache[uniformName] = null;
  22971. this._engine.setIntArray4(this.getUniform(uniformName), array);
  22972. return this;
  22973. };
  22974. Effect.prototype.setFloatArray = function (uniformName, array) {
  22975. this._valueCache[uniformName] = null;
  22976. this._engine.setFloatArray(this.getUniform(uniformName), array);
  22977. return this;
  22978. };
  22979. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  22980. this._valueCache[uniformName] = null;
  22981. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  22982. return this;
  22983. };
  22984. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  22985. this._valueCache[uniformName] = null;
  22986. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  22987. return this;
  22988. };
  22989. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  22990. this._valueCache[uniformName] = null;
  22991. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  22992. return this;
  22993. };
  22994. Effect.prototype.setArray = function (uniformName, array) {
  22995. this._valueCache[uniformName] = null;
  22996. this._engine.setArray(this.getUniform(uniformName), array);
  22997. return this;
  22998. };
  22999. Effect.prototype.setArray2 = function (uniformName, array) {
  23000. this._valueCache[uniformName] = null;
  23001. this._engine.setArray2(this.getUniform(uniformName), array);
  23002. return this;
  23003. };
  23004. Effect.prototype.setArray3 = function (uniformName, array) {
  23005. this._valueCache[uniformName] = null;
  23006. this._engine.setArray3(this.getUniform(uniformName), array);
  23007. return this;
  23008. };
  23009. Effect.prototype.setArray4 = function (uniformName, array) {
  23010. this._valueCache[uniformName] = null;
  23011. this._engine.setArray4(this.getUniform(uniformName), array);
  23012. return this;
  23013. };
  23014. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23015. if (!matrices) {
  23016. return;
  23017. }
  23018. this._valueCache[uniformName] = null;
  23019. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23020. return this;
  23021. };
  23022. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23023. if (this._cacheMatrix(uniformName, matrix)) {
  23024. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23025. }
  23026. return this;
  23027. };
  23028. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23029. this._valueCache[uniformName] = null;
  23030. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23031. return this;
  23032. };
  23033. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23034. this._valueCache[uniformName] = null;
  23035. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23036. return this;
  23037. };
  23038. Effect.prototype.setFloat = function (uniformName, value) {
  23039. var cache = this._valueCache[uniformName];
  23040. if (cache !== undefined && cache === value)
  23041. return this;
  23042. this._valueCache[uniformName] = value;
  23043. this._engine.setFloat(this.getUniform(uniformName), value);
  23044. return this;
  23045. };
  23046. Effect.prototype.setBool = function (uniformName, bool) {
  23047. var cache = this._valueCache[uniformName];
  23048. if (cache !== undefined && cache === bool)
  23049. return this;
  23050. this._valueCache[uniformName] = bool;
  23051. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23052. return this;
  23053. };
  23054. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23055. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23056. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23057. }
  23058. return this;
  23059. };
  23060. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23061. if (this._cacheFloat2(uniformName, x, y)) {
  23062. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23063. }
  23064. return this;
  23065. };
  23066. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23067. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23068. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23069. }
  23070. return this;
  23071. };
  23072. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23073. if (this._cacheFloat3(uniformName, x, y, z)) {
  23074. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23075. }
  23076. return this;
  23077. };
  23078. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23079. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23080. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23081. }
  23082. return this;
  23083. };
  23084. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23085. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23086. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23087. }
  23088. return this;
  23089. };
  23090. Effect.prototype.setColor3 = function (uniformName, color3) {
  23091. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23092. this._engine.setColor3(this.getUniform(uniformName), color3);
  23093. }
  23094. return this;
  23095. };
  23096. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23097. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23098. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23099. }
  23100. return this;
  23101. };
  23102. Effect.prototype._recombineShader = function (node) {
  23103. if (node.define) {
  23104. if (node.condition) {
  23105. var defineIndex = this.defines.indexOf("#define " + node.define);
  23106. if (defineIndex === -1) {
  23107. return null;
  23108. }
  23109. var nextComma = this.defines.indexOf("\n", defineIndex);
  23110. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23111. var condition = defineValue + node.condition;
  23112. if (!eval(condition)) {
  23113. return null;
  23114. }
  23115. }
  23116. else if (node.ndef) {
  23117. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23118. return null;
  23119. }
  23120. }
  23121. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23122. return null;
  23123. }
  23124. }
  23125. var result = "";
  23126. for (var index = 0; index < node.children.length; index++) {
  23127. var line = node.children[index];
  23128. if (line.children) {
  23129. var combined = this._recombineShader(line);
  23130. if (combined !== null) {
  23131. result += combined + "\r\n";
  23132. }
  23133. continue;
  23134. }
  23135. if (line.length > 0) {
  23136. result += line + "\r\n";
  23137. }
  23138. }
  23139. return result;
  23140. };
  23141. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23142. var root = {
  23143. children: []
  23144. };
  23145. var currentNode = root;
  23146. var lines = shaderString.split("\n");
  23147. for (var index = 0; index < lines.length; index++) {
  23148. var line = lines[index].trim();
  23149. // #ifdef
  23150. var pos = line.indexOf("#ifdef ");
  23151. if (pos !== -1) {
  23152. var define = line.substr(pos + 7);
  23153. var newNode = {
  23154. condition: null,
  23155. ndef: false,
  23156. define: define,
  23157. children: [],
  23158. parent: currentNode
  23159. };
  23160. currentNode.children.push(newNode);
  23161. currentNode = newNode;
  23162. continue;
  23163. }
  23164. // #ifndef
  23165. var pos = line.indexOf("#ifndef ");
  23166. if (pos !== -1) {
  23167. var define = line.substr(pos + 8);
  23168. newNode = {
  23169. condition: null,
  23170. define: define,
  23171. ndef: true,
  23172. children: [],
  23173. parent: currentNode
  23174. };
  23175. currentNode.children.push(newNode);
  23176. currentNode = newNode;
  23177. continue;
  23178. }
  23179. // #if
  23180. var pos = line.indexOf("#if ");
  23181. if (pos !== -1) {
  23182. var define = line.substr(pos + 4).trim();
  23183. var conditionPos = define.indexOf(" ");
  23184. newNode = {
  23185. condition: define.substr(conditionPos + 1),
  23186. define: define.substr(0, conditionPos),
  23187. ndef: false,
  23188. children: [],
  23189. parent: currentNode
  23190. };
  23191. currentNode.children.push(newNode);
  23192. currentNode = newNode;
  23193. continue;
  23194. }
  23195. // #endif
  23196. pos = line.indexOf("#endif");
  23197. if (pos !== -1) {
  23198. currentNode = currentNode.parent;
  23199. continue;
  23200. }
  23201. currentNode.children.push(line);
  23202. }
  23203. // Recombine
  23204. return this._recombineShader(root);
  23205. };
  23206. return Effect;
  23207. }());
  23208. Effect._uniqueIdSeed = 0;
  23209. Effect._baseCache = {};
  23210. // Statics
  23211. Effect.ShadersStore = {};
  23212. Effect.IncludesShadersStore = {};
  23213. BABYLON.Effect = Effect;
  23214. })(BABYLON || (BABYLON = {}));
  23215. //# sourceMappingURL=babylon.effect.js.map
  23216. var BABYLON;
  23217. (function (BABYLON) {
  23218. var MaterialHelper = (function () {
  23219. function MaterialHelper() {
  23220. }
  23221. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23222. if (defines._areMiscDirty) {
  23223. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23224. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23225. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23226. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23227. }
  23228. };
  23229. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  23230. var changed = false;
  23231. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23232. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23233. changed = true;
  23234. }
  23235. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  23236. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23237. changed = true;
  23238. }
  23239. if (defines["INSTANCES"] !== useInstances) {
  23240. defines["INSTANCES"] = useInstances;
  23241. changed = true;
  23242. }
  23243. if (changed) {
  23244. defines.markAsUnprocessed();
  23245. }
  23246. };
  23247. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23248. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23249. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23250. return;
  23251. }
  23252. defines._normals = defines._needNormals;
  23253. defines._uvs = defines._needUVs;
  23254. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23255. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23256. defines["TANGENT"] = true;
  23257. }
  23258. if (defines._needUVs) {
  23259. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23260. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23261. }
  23262. else {
  23263. defines["UV1"] = false;
  23264. defines["UV2"] = false;
  23265. }
  23266. if (useVertexColor) {
  23267. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23268. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23269. }
  23270. if (useBones) {
  23271. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23272. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23273. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23274. }
  23275. else {
  23276. defines["NUM_BONE_INFLUENCERS"] = 0;
  23277. defines["BonesPerMesh"] = 0;
  23278. }
  23279. }
  23280. if (useMorphTargets) {
  23281. if (mesh.morphTargetManager) {
  23282. var manager = mesh.morphTargetManager;
  23283. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23284. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23285. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23286. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23287. }
  23288. else {
  23289. defines["MORPHTARGETS_TANGENT"] = false;
  23290. defines["MORPHTARGETS_NORMAL"] = false;
  23291. defines["MORPHTARGETS"] = false;
  23292. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23293. }
  23294. }
  23295. };
  23296. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23297. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23298. if (disableLighting === void 0) { disableLighting = false; }
  23299. if (!defines._areLightsDirty) {
  23300. return defines._needNormals;
  23301. }
  23302. var lightIndex = 0;
  23303. var needNormals = false;
  23304. var needRebuild = false;
  23305. var lightmapMode = false;
  23306. var shadowEnabled = false;
  23307. var specularEnabled = false;
  23308. if (scene.lightsEnabled && !disableLighting) {
  23309. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23310. var light = _a[_i];
  23311. needNormals = true;
  23312. if (defines["LIGHT" + lightIndex] === undefined) {
  23313. needRebuild = true;
  23314. }
  23315. defines["LIGHT" + lightIndex] = true;
  23316. defines["SPOTLIGHT" + lightIndex] = false;
  23317. defines["HEMILIGHT" + lightIndex] = false;
  23318. defines["POINTLIGHT" + lightIndex] = false;
  23319. defines["DIRLIGHT" + lightIndex] = false;
  23320. var type;
  23321. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23322. type = "SPOTLIGHT" + lightIndex;
  23323. }
  23324. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23325. type = "HEMILIGHT" + lightIndex;
  23326. }
  23327. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23328. type = "POINTLIGHT" + lightIndex;
  23329. }
  23330. else {
  23331. type = "DIRLIGHT" + lightIndex;
  23332. }
  23333. defines[type] = true;
  23334. // Specular
  23335. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23336. specularEnabled = true;
  23337. }
  23338. // Shadows
  23339. defines["SHADOW" + lightIndex] = false;
  23340. defines["SHADOWPCF" + lightIndex] = false;
  23341. defines["SHADOWESM" + lightIndex] = false;
  23342. defines["SHADOWCUBE" + lightIndex] = false;
  23343. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23344. var shadowGenerator = light.getShadowGenerator();
  23345. if (shadowGenerator) {
  23346. shadowEnabled = true;
  23347. shadowGenerator.prepareDefines(defines, lightIndex);
  23348. }
  23349. }
  23350. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23351. lightmapMode = true;
  23352. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23353. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23354. }
  23355. else {
  23356. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23357. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23358. }
  23359. lightIndex++;
  23360. if (lightIndex === maxSimultaneousLights)
  23361. break;
  23362. }
  23363. }
  23364. defines["SPECULARTERM"] = specularEnabled;
  23365. defines["SHADOWS"] = shadowEnabled;
  23366. // Resetting all other lights if any
  23367. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23368. if (defines["LIGHT" + index] !== undefined) {
  23369. defines["LIGHT" + index] = false;
  23370. }
  23371. }
  23372. var caps = scene.getEngine().getCaps();
  23373. if (defines["SHADOWFLOAT"] === undefined) {
  23374. needRebuild = true;
  23375. }
  23376. defines["SHADOWFLOAT"] = shadowEnabled &&
  23377. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23378. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23379. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23380. if (needRebuild) {
  23381. defines.rebuild();
  23382. }
  23383. return needNormals;
  23384. };
  23385. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23386. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23387. var uniformsList, uniformBuffersList, samplersList, defines;
  23388. if (uniformsListOrOptions.uniformsNames) {
  23389. var options = uniformsListOrOptions;
  23390. uniformsList = options.uniformsNames;
  23391. uniformBuffersList = options.uniformBuffersNames;
  23392. samplersList = options.samplers;
  23393. defines = options.defines;
  23394. maxSimultaneousLights = options.maxSimultaneousLights;
  23395. }
  23396. else {
  23397. uniformsList = uniformsListOrOptions;
  23398. }
  23399. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23400. if (!defines["LIGHT" + lightIndex]) {
  23401. break;
  23402. }
  23403. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23404. if (uniformBuffersList) {
  23405. uniformBuffersList.push("Light" + lightIndex);
  23406. }
  23407. samplersList.push("shadowSampler" + lightIndex);
  23408. }
  23409. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23410. uniformsList.push("morphTargetInfluences");
  23411. }
  23412. };
  23413. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23414. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23415. if (!defines["SHADOWS"]) {
  23416. return;
  23417. }
  23418. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23419. if (!defines["LIGHT" + lightIndex]) {
  23420. break;
  23421. }
  23422. if (lightIndex > 0) {
  23423. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23424. }
  23425. if (defines["SHADOW" + lightIndex]) {
  23426. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23427. }
  23428. if (defines["SHADOWPCF" + lightIndex]) {
  23429. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23430. }
  23431. if (defines["SHADOWESM" + lightIndex]) {
  23432. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23433. }
  23434. }
  23435. };
  23436. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23437. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23438. if (influencers > 0) {
  23439. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23440. var manager = mesh.morphTargetManager;
  23441. var normal = manager.supportsNormals && defines["NORMAL"];
  23442. var tangent = manager.supportsTangents && defines["TANGENT"];
  23443. for (var index = 0; index < influencers; index++) {
  23444. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23445. if (normal) {
  23446. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23447. }
  23448. if (tangent) {
  23449. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23450. }
  23451. if (attribs.length > maxAttributesCount) {
  23452. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23453. }
  23454. }
  23455. }
  23456. };
  23457. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23458. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23459. fallbacks.addCPUSkinningFallback(0, mesh);
  23460. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23461. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23462. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23463. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23464. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23465. }
  23466. }
  23467. };
  23468. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23469. if (defines["INSTANCES"]) {
  23470. attribs.push("world0");
  23471. attribs.push("world1");
  23472. attribs.push("world2");
  23473. attribs.push("world3");
  23474. }
  23475. };
  23476. // Bindings
  23477. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23478. if (light.shadowEnabled && mesh.receiveShadows) {
  23479. var shadowGenerator = light.getShadowGenerator();
  23480. if (shadowGenerator) {
  23481. depthValuesAlreadySet = shadowGenerator.bindShadowLight(lightIndex, effect, depthValuesAlreadySet);
  23482. }
  23483. }
  23484. return depthValuesAlreadySet;
  23485. };
  23486. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23487. light.transferToEffect(effect, lightIndex + "");
  23488. };
  23489. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23490. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23491. var lightIndex = 0;
  23492. var depthValuesAlreadySet = false;
  23493. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23494. var light = _a[_i];
  23495. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23496. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23497. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23498. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  23499. if (defines["SPECULARTERM"]) {
  23500. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23501. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23502. }
  23503. // Shadows
  23504. if (scene.shadowsEnabled) {
  23505. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  23506. }
  23507. light._uniformBuffer.update();
  23508. lightIndex++;
  23509. if (lightIndex === maxSimultaneousLights)
  23510. break;
  23511. }
  23512. };
  23513. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23514. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23515. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23516. effect.setColor3("vFogColor", scene.fogColor);
  23517. }
  23518. };
  23519. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23520. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23521. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23522. if (matrices) {
  23523. effect.setMatrices("mBones", matrices);
  23524. }
  23525. }
  23526. };
  23527. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23528. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23529. return;
  23530. }
  23531. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23532. };
  23533. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23534. if (defines["LOGARITHMICDEPTH"]) {
  23535. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23536. }
  23537. };
  23538. MaterialHelper.BindClipPlane = function (effect, scene) {
  23539. if (scene.clipPlane) {
  23540. var clipPlane = scene.clipPlane;
  23541. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23542. }
  23543. };
  23544. return MaterialHelper;
  23545. }());
  23546. BABYLON.MaterialHelper = MaterialHelper;
  23547. })(BABYLON || (BABYLON = {}));
  23548. //# sourceMappingURL=babylon.materialHelper.js.map
  23549. var BABYLON;
  23550. (function (BABYLON) {
  23551. var MaterialDefines = (function () {
  23552. function MaterialDefines() {
  23553. this._isDirty = true;
  23554. this._areLightsDirty = true;
  23555. this._areAttributesDirty = true;
  23556. this._areTexturesDirty = true;
  23557. this._areFresnelDirty = true;
  23558. this._areMiscDirty = true;
  23559. this._normals = false;
  23560. this._uvs = false;
  23561. this._needNormals = false;
  23562. this._needUVs = false;
  23563. }
  23564. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23565. get: function () {
  23566. return this._isDirty;
  23567. },
  23568. enumerable: true,
  23569. configurable: true
  23570. });
  23571. MaterialDefines.prototype.markAsProcessed = function () {
  23572. this._isDirty = false;
  23573. this._areAttributesDirty = false;
  23574. this._areTexturesDirty = false;
  23575. this._areFresnelDirty = false;
  23576. this._areLightsDirty = false;
  23577. this._areMiscDirty = false;
  23578. };
  23579. MaterialDefines.prototype.markAsUnprocessed = function () {
  23580. this._isDirty = true;
  23581. };
  23582. MaterialDefines.prototype.markAllAsDirty = function () {
  23583. this._areTexturesDirty = true;
  23584. this._areAttributesDirty = true;
  23585. this._areLightsDirty = true;
  23586. this._areFresnelDirty = true;
  23587. this._areMiscDirty = true;
  23588. this._isDirty = true;
  23589. };
  23590. MaterialDefines.prototype.markAsLightDirty = function () {
  23591. this._areLightsDirty = true;
  23592. this._isDirty = true;
  23593. };
  23594. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23595. this._areAttributesDirty = true;
  23596. this._isDirty = true;
  23597. };
  23598. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23599. this._areTexturesDirty = true;
  23600. this._isDirty = true;
  23601. };
  23602. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23603. this._areFresnelDirty = true;
  23604. this._isDirty = true;
  23605. };
  23606. MaterialDefines.prototype.markAsMiscDirty = function () {
  23607. this._areMiscDirty = true;
  23608. this._isDirty = true;
  23609. };
  23610. MaterialDefines.prototype.rebuild = function () {
  23611. if (this._keys) {
  23612. delete this._keys;
  23613. }
  23614. this._keys = [];
  23615. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23616. var key = _a[_i];
  23617. if (key[0] === "_") {
  23618. continue;
  23619. }
  23620. this._keys.push(key);
  23621. }
  23622. };
  23623. MaterialDefines.prototype.isEqual = function (other) {
  23624. if (this._keys.length !== other._keys.length) {
  23625. return false;
  23626. }
  23627. for (var index = 0; index < this._keys.length; index++) {
  23628. var prop = this._keys[index];
  23629. if (this[prop] !== other[prop]) {
  23630. return false;
  23631. }
  23632. }
  23633. return true;
  23634. };
  23635. MaterialDefines.prototype.cloneTo = function (other) {
  23636. if (this._keys.length !== other._keys.length) {
  23637. other._keys = this._keys.slice(0);
  23638. }
  23639. for (var index = 0; index < this._keys.length; index++) {
  23640. var prop = this._keys[index];
  23641. other[prop] = this[prop];
  23642. }
  23643. };
  23644. MaterialDefines.prototype.reset = function () {
  23645. for (var index = 0; index < this._keys.length; index++) {
  23646. var prop = this._keys[index];
  23647. if (typeof (this[prop]) === "number") {
  23648. this[prop] = 0;
  23649. }
  23650. else {
  23651. this[prop] = false;
  23652. }
  23653. }
  23654. };
  23655. MaterialDefines.prototype.toString = function () {
  23656. var result = "";
  23657. for (var index = 0; index < this._keys.length; index++) {
  23658. var prop = this._keys[index];
  23659. var value = this[prop];
  23660. if (typeof (value) === "number") {
  23661. result += "#define " + prop + " " + this[prop] + "\n";
  23662. }
  23663. else if (value) {
  23664. result += "#define " + prop + "\n";
  23665. }
  23666. }
  23667. return result;
  23668. };
  23669. return MaterialDefines;
  23670. }());
  23671. BABYLON.MaterialDefines = MaterialDefines;
  23672. var Material = (function () {
  23673. function Material(name, scene, doNotAdd) {
  23674. this.checkReadyOnEveryCall = false;
  23675. this.checkReadyOnlyOnce = false;
  23676. this.state = "";
  23677. this.alpha = 1.0;
  23678. this._backFaceCulling = true;
  23679. this.doNotSerialize = false;
  23680. this.storeEffectOnSubMeshes = false;
  23681. /**
  23682. * An event triggered when the material is disposed.
  23683. * @type {BABYLON.Observable}
  23684. */
  23685. this.onDisposeObservable = new BABYLON.Observable();
  23686. /**
  23687. * An event triggered when the material is bound.
  23688. * @type {BABYLON.Observable}
  23689. */
  23690. this.onBindObservable = new BABYLON.Observable();
  23691. /**
  23692. * An event triggered when the material is unbound.
  23693. * @type {BABYLON.Observable}
  23694. */
  23695. this.onUnBindObservable = new BABYLON.Observable();
  23696. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23697. this.disableDepthWrite = false;
  23698. this._fogEnabled = true;
  23699. this.pointSize = 1.0;
  23700. this.zOffset = 0;
  23701. this._wasPreviouslyReady = false;
  23702. this._fillMode = Material.TriangleFillMode;
  23703. this.name = name;
  23704. this.id = name;
  23705. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23706. if (this._scene.useRightHandedSystem) {
  23707. this.sideOrientation = Material.ClockWiseSideOrientation;
  23708. }
  23709. else {
  23710. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23711. }
  23712. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23713. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23714. if (!doNotAdd) {
  23715. this._scene.materials.push(this);
  23716. }
  23717. }
  23718. Object.defineProperty(Material, "TriangleFillMode", {
  23719. get: function () {
  23720. return Material._TriangleFillMode;
  23721. },
  23722. enumerable: true,
  23723. configurable: true
  23724. });
  23725. Object.defineProperty(Material, "WireFrameFillMode", {
  23726. get: function () {
  23727. return Material._WireFrameFillMode;
  23728. },
  23729. enumerable: true,
  23730. configurable: true
  23731. });
  23732. Object.defineProperty(Material, "PointFillMode", {
  23733. get: function () {
  23734. return Material._PointFillMode;
  23735. },
  23736. enumerable: true,
  23737. configurable: true
  23738. });
  23739. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23740. get: function () {
  23741. return Material._ClockWiseSideOrientation;
  23742. },
  23743. enumerable: true,
  23744. configurable: true
  23745. });
  23746. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23747. get: function () {
  23748. return Material._CounterClockWiseSideOrientation;
  23749. },
  23750. enumerable: true,
  23751. configurable: true
  23752. });
  23753. Object.defineProperty(Material, "TextureDirtyFlag", {
  23754. get: function () {
  23755. return Material._TextureDirtyFlag;
  23756. },
  23757. enumerable: true,
  23758. configurable: true
  23759. });
  23760. Object.defineProperty(Material, "LightDirtyFlag", {
  23761. get: function () {
  23762. return Material._LightDirtyFlag;
  23763. },
  23764. enumerable: true,
  23765. configurable: true
  23766. });
  23767. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23768. get: function () {
  23769. return Material._FresnelDirtyFlag;
  23770. },
  23771. enumerable: true,
  23772. configurable: true
  23773. });
  23774. Object.defineProperty(Material, "AttributesDirtyFlag", {
  23775. get: function () {
  23776. return Material._AttributesDirtyFlag;
  23777. },
  23778. enumerable: true,
  23779. configurable: true
  23780. });
  23781. Object.defineProperty(Material, "MiscDirtyFlag", {
  23782. get: function () {
  23783. return Material._MiscDirtyFlag;
  23784. },
  23785. enumerable: true,
  23786. configurable: true
  23787. });
  23788. Object.defineProperty(Material.prototype, "backFaceCulling", {
  23789. get: function () {
  23790. return this._backFaceCulling;
  23791. },
  23792. set: function (value) {
  23793. if (this._backFaceCulling === value) {
  23794. return;
  23795. }
  23796. this._backFaceCulling = value;
  23797. this.markAsDirty(Material.TextureDirtyFlag);
  23798. },
  23799. enumerable: true,
  23800. configurable: true
  23801. });
  23802. Object.defineProperty(Material.prototype, "onDispose", {
  23803. set: function (callback) {
  23804. if (this._onDisposeObserver) {
  23805. this.onDisposeObservable.remove(this._onDisposeObserver);
  23806. }
  23807. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23808. },
  23809. enumerable: true,
  23810. configurable: true
  23811. });
  23812. Object.defineProperty(Material.prototype, "onBind", {
  23813. set: function (callback) {
  23814. if (this._onBindObserver) {
  23815. this.onBindObservable.remove(this._onBindObserver);
  23816. }
  23817. this._onBindObserver = this.onBindObservable.add(callback);
  23818. },
  23819. enumerable: true,
  23820. configurable: true
  23821. });
  23822. Object.defineProperty(Material.prototype, "fogEnabled", {
  23823. get: function () {
  23824. return this._fogEnabled;
  23825. },
  23826. set: function (value) {
  23827. if (this._fogEnabled === value) {
  23828. return;
  23829. }
  23830. this._fogEnabled = value;
  23831. this.markAsDirty(Material.MiscDirtyFlag);
  23832. },
  23833. enumerable: true,
  23834. configurable: true
  23835. });
  23836. Object.defineProperty(Material.prototype, "wireframe", {
  23837. get: function () {
  23838. return this._fillMode === Material.WireFrameFillMode;
  23839. },
  23840. set: function (value) {
  23841. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23842. },
  23843. enumerable: true,
  23844. configurable: true
  23845. });
  23846. Object.defineProperty(Material.prototype, "pointsCloud", {
  23847. get: function () {
  23848. return this._fillMode === Material.PointFillMode;
  23849. },
  23850. set: function (value) {
  23851. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23852. },
  23853. enumerable: true,
  23854. configurable: true
  23855. });
  23856. Object.defineProperty(Material.prototype, "fillMode", {
  23857. get: function () {
  23858. return this._fillMode;
  23859. },
  23860. set: function (value) {
  23861. if (this._fillMode === value) {
  23862. return;
  23863. }
  23864. this._fillMode = value;
  23865. this.markAsDirty(Material.MiscDirtyFlag);
  23866. },
  23867. enumerable: true,
  23868. configurable: true
  23869. });
  23870. /**
  23871. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23872. * subclasses should override adding information pertainent to themselves
  23873. */
  23874. Material.prototype.toString = function (fullDetails) {
  23875. var ret = "Name: " + this.name;
  23876. if (fullDetails) {
  23877. }
  23878. return ret;
  23879. };
  23880. /**
  23881. * Child classes can use it to update shaders
  23882. */
  23883. Material.prototype.markAsDirty = function (flag) {
  23884. };
  23885. Material.prototype.getClassName = function () {
  23886. return "Material";
  23887. };
  23888. Object.defineProperty(Material.prototype, "isFrozen", {
  23889. get: function () {
  23890. return this.checkReadyOnlyOnce;
  23891. },
  23892. enumerable: true,
  23893. configurable: true
  23894. });
  23895. Material.prototype.freeze = function () {
  23896. this.checkReadyOnlyOnce = true;
  23897. };
  23898. Material.prototype.unfreeze = function () {
  23899. this.checkReadyOnlyOnce = false;
  23900. };
  23901. Material.prototype.isReady = function (mesh, useInstances) {
  23902. return true;
  23903. };
  23904. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  23905. return false;
  23906. };
  23907. Material.prototype.getEffect = function () {
  23908. return this._effect;
  23909. };
  23910. Material.prototype.getScene = function () {
  23911. return this._scene;
  23912. };
  23913. Material.prototype.needAlphaBlending = function () {
  23914. return (this.alpha < 1.0);
  23915. };
  23916. Material.prototype.needAlphaTesting = function () {
  23917. return false;
  23918. };
  23919. Material.prototype.getAlphaTestTexture = function () {
  23920. return null;
  23921. };
  23922. Material.prototype.markDirty = function () {
  23923. this._wasPreviouslyReady = false;
  23924. };
  23925. Material.prototype._preBind = function (effect) {
  23926. var engine = this._scene.getEngine();
  23927. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  23928. engine.enableEffect(effect ? effect : this._effect);
  23929. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  23930. };
  23931. Material.prototype.bind = function (world, mesh) {
  23932. };
  23933. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  23934. };
  23935. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23936. };
  23937. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  23938. sceneUbo.bindToEffect(effect, "Scene");
  23939. };
  23940. Material.prototype.bindView = function (effect) {
  23941. if (!this._useUBO) {
  23942. effect.setMatrix("view", this.getScene().getViewMatrix());
  23943. }
  23944. else {
  23945. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23946. }
  23947. };
  23948. Material.prototype.bindViewProjection = function (effect) {
  23949. if (!this._useUBO) {
  23950. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23951. }
  23952. else {
  23953. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23954. }
  23955. };
  23956. Material.prototype._afterBind = function (mesh) {
  23957. this._scene._cachedMaterial = this;
  23958. this.onBindObservable.notifyObservers(mesh);
  23959. if (this.disableDepthWrite) {
  23960. var engine = this._scene.getEngine();
  23961. this._cachedDepthWriteState = engine.getDepthWrite();
  23962. engine.setDepthWrite(false);
  23963. }
  23964. };
  23965. Material.prototype.unbind = function () {
  23966. this.onUnBindObservable.notifyObservers(this);
  23967. if (this.disableDepthWrite) {
  23968. var engine = this._scene.getEngine();
  23969. engine.setDepthWrite(this._cachedDepthWriteState);
  23970. }
  23971. };
  23972. Material.prototype.clone = function (name) {
  23973. return null;
  23974. };
  23975. Material.prototype.getBindedMeshes = function () {
  23976. var result = new Array();
  23977. for (var index = 0; index < this._scene.meshes.length; index++) {
  23978. var mesh = this._scene.meshes[index];
  23979. if (mesh.material === this) {
  23980. result.push(mesh);
  23981. }
  23982. }
  23983. return result;
  23984. };
  23985. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23986. // Animations
  23987. this.getScene().stopAnimation(this);
  23988. // Remove from scene
  23989. var index = this._scene.materials.indexOf(this);
  23990. if (index >= 0) {
  23991. this._scene.materials.splice(index, 1);
  23992. }
  23993. // Remove from meshes
  23994. for (index = 0; index < this._scene.meshes.length; index++) {
  23995. var mesh = this._scene.meshes[index];
  23996. if (mesh.material === this) {
  23997. mesh.material = null;
  23998. if (mesh.geometry) {
  23999. var geometry = mesh.geometry;
  24000. if (this.storeEffectOnSubMeshes) {
  24001. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24002. var subMesh = _a[_i];
  24003. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24004. }
  24005. }
  24006. else {
  24007. geometry._releaseVertexArrayObject(this._effect);
  24008. }
  24009. }
  24010. }
  24011. }
  24012. this._uniformBuffer.dispose();
  24013. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24014. if (forceDisposeEffect && this._effect) {
  24015. if (this.storeEffectOnSubMeshes) {
  24016. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24017. var subMesh = _c[_b];
  24018. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24019. }
  24020. }
  24021. else {
  24022. this._scene.getEngine()._releaseEffect(this._effect);
  24023. }
  24024. this._effect = null;
  24025. }
  24026. // Callback
  24027. this.onDisposeObservable.notifyObservers(this);
  24028. this.onDisposeObservable.clear();
  24029. this.onBindObservable.clear();
  24030. this.onUnBindObservable.clear();
  24031. };
  24032. Material.prototype.serialize = function () {
  24033. return BABYLON.SerializationHelper.Serialize(this);
  24034. };
  24035. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24036. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24037. multiMaterial.id = parsedMultiMaterial.id;
  24038. if (BABYLON.Tags) {
  24039. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24040. }
  24041. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24042. var subMatId = parsedMultiMaterial.materials[matIndex];
  24043. if (subMatId) {
  24044. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24045. }
  24046. else {
  24047. multiMaterial.subMaterials.push(null);
  24048. }
  24049. }
  24050. return multiMaterial;
  24051. };
  24052. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24053. if (!parsedMaterial.customType) {
  24054. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24055. }
  24056. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && !parsedMaterial.overloadedAlbedo) {
  24057. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24058. if (!BABYLON.LegacyPBRMaterial) {
  24059. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24060. return;
  24061. }
  24062. }
  24063. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24064. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24065. ;
  24066. };
  24067. return Material;
  24068. }());
  24069. Material._TriangleFillMode = 0;
  24070. Material._WireFrameFillMode = 1;
  24071. Material._PointFillMode = 2;
  24072. Material._ClockWiseSideOrientation = 0;
  24073. Material._CounterClockWiseSideOrientation = 1;
  24074. Material._TextureDirtyFlag = 1;
  24075. Material._LightDirtyFlag = 2;
  24076. Material._FresnelDirtyFlag = 4;
  24077. Material._AttributesDirtyFlag = 8;
  24078. Material._MiscDirtyFlag = 16;
  24079. __decorate([
  24080. BABYLON.serialize()
  24081. ], Material.prototype, "id", void 0);
  24082. __decorate([
  24083. BABYLON.serialize()
  24084. ], Material.prototype, "name", void 0);
  24085. __decorate([
  24086. BABYLON.serialize()
  24087. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24088. __decorate([
  24089. BABYLON.serialize()
  24090. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24091. __decorate([
  24092. BABYLON.serialize()
  24093. ], Material.prototype, "state", void 0);
  24094. __decorate([
  24095. BABYLON.serialize()
  24096. ], Material.prototype, "alpha", void 0);
  24097. __decorate([
  24098. BABYLON.serialize("backFaceCulling")
  24099. ], Material.prototype, "_backFaceCulling", void 0);
  24100. __decorate([
  24101. BABYLON.serialize()
  24102. ], Material.prototype, "sideOrientation", void 0);
  24103. __decorate([
  24104. BABYLON.serialize()
  24105. ], Material.prototype, "alphaMode", void 0);
  24106. __decorate([
  24107. BABYLON.serialize()
  24108. ], Material.prototype, "disableDepthWrite", void 0);
  24109. __decorate([
  24110. BABYLON.serialize("fogEnabled")
  24111. ], Material.prototype, "_fogEnabled", void 0);
  24112. __decorate([
  24113. BABYLON.serialize()
  24114. ], Material.prototype, "pointSize", void 0);
  24115. __decorate([
  24116. BABYLON.serialize()
  24117. ], Material.prototype, "zOffset", void 0);
  24118. __decorate([
  24119. BABYLON.serialize()
  24120. ], Material.prototype, "wireframe", null);
  24121. __decorate([
  24122. BABYLON.serialize()
  24123. ], Material.prototype, "pointsCloud", null);
  24124. __decorate([
  24125. BABYLON.serialize()
  24126. ], Material.prototype, "fillMode", null);
  24127. BABYLON.Material = Material;
  24128. })(BABYLON || (BABYLON = {}));
  24129. //# sourceMappingURL=babylon.material.js.map
  24130. var BABYLON;
  24131. (function (BABYLON) {
  24132. var UniformBuffer = (function () {
  24133. /**
  24134. * Uniform buffer objects.
  24135. *
  24136. * Handles blocks of uniform on the GPU.
  24137. *
  24138. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24139. *
  24140. * For more information, please refer to :
  24141. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24142. */
  24143. function UniformBuffer(engine, data, dynamic) {
  24144. this._engine = engine;
  24145. this._noUBO = engine.webGLVersion === 1;
  24146. this._dynamic = dynamic;
  24147. this._data = data || [];
  24148. this._uniformLocations = {};
  24149. this._uniformSizes = {};
  24150. this._uniformLocationPointer = 0;
  24151. this._needSync = false;
  24152. if (this._noUBO) {
  24153. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24154. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24155. this.updateFloat = this._updateFloatForEffect;
  24156. this.updateFloat2 = this._updateFloat2ForEffect;
  24157. this.updateFloat3 = this._updateFloat3ForEffect;
  24158. this.updateFloat4 = this._updateFloat4ForEffect;
  24159. this.updateMatrix = this._updateMatrixForEffect;
  24160. this.updateVector3 = this._updateVector3ForEffect;
  24161. this.updateVector4 = this._updateVector4ForEffect;
  24162. this.updateColor3 = this._updateColor3ForEffect;
  24163. this.updateColor4 = this._updateColor4ForEffect;
  24164. }
  24165. else {
  24166. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24167. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24168. this.updateFloat = this._updateFloatForUniform;
  24169. this.updateFloat2 = this._updateFloat2ForUniform;
  24170. this.updateFloat3 = this._updateFloat3ForUniform;
  24171. this.updateFloat4 = this._updateFloat4ForUniform;
  24172. this.updateMatrix = this._updateMatrixForUniform;
  24173. this.updateVector3 = this._updateVector3ForUniform;
  24174. this.updateVector4 = this._updateVector4ForUniform;
  24175. this.updateColor3 = this._updateColor3ForUniform;
  24176. this.updateColor4 = this._updateColor4ForUniform;
  24177. }
  24178. }
  24179. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24180. // Properties
  24181. /**
  24182. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24183. * or just falling back on setUniformXXX calls.
  24184. */
  24185. get: function () {
  24186. return !this._noUBO;
  24187. },
  24188. enumerable: true,
  24189. configurable: true
  24190. });
  24191. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24192. /**
  24193. * Indicates if the WebGL underlying uniform buffer is in sync
  24194. * with the javascript cache data.
  24195. */
  24196. get: function () {
  24197. return !this._needSync;
  24198. },
  24199. enumerable: true,
  24200. configurable: true
  24201. });
  24202. /**
  24203. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24204. * Also, a dynamic UniformBuffer will disable cache verification and always
  24205. * update the underlying WebGL uniform buffer to the GPU.
  24206. */
  24207. UniformBuffer.prototype.isDynamic = function () {
  24208. return this._dynamic;
  24209. };
  24210. /**
  24211. * The data cache on JS side.
  24212. */
  24213. UniformBuffer.prototype.getData = function () {
  24214. return this._bufferData;
  24215. };
  24216. /**
  24217. * The underlying WebGL Uniform buffer.
  24218. */
  24219. UniformBuffer.prototype.getBuffer = function () {
  24220. return this._buffer;
  24221. };
  24222. /**
  24223. * std140 layout specifies how to align data within an UBO structure.
  24224. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24225. * for specs.
  24226. */
  24227. UniformBuffer.prototype._fillAlignment = function (size) {
  24228. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24229. // and 4x4 matrices
  24230. // TODO : change if other types are used
  24231. var alignment;
  24232. if (size <= 2) {
  24233. alignment = size;
  24234. }
  24235. else {
  24236. alignment = 4;
  24237. }
  24238. if ((this._uniformLocationPointer % alignment) !== 0) {
  24239. var oldPointer = this._uniformLocationPointer;
  24240. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24241. var diff = this._uniformLocationPointer - oldPointer;
  24242. for (var i = 0; i < diff; i++) {
  24243. this._data.push(0);
  24244. }
  24245. }
  24246. };
  24247. /**
  24248. * Adds an uniform in the buffer.
  24249. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24250. * for the layout to be correct !
  24251. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24252. * @param {number|number[]} size Data size, or data directly.
  24253. */
  24254. UniformBuffer.prototype.addUniform = function (name, size) {
  24255. if (this._noUBO) {
  24256. return;
  24257. }
  24258. if (this._uniformLocations[name] !== undefined) {
  24259. // Already existing uniform
  24260. return;
  24261. }
  24262. // This function must be called in the order of the shader layout !
  24263. // size can be the size of the uniform, or data directly
  24264. var data;
  24265. if (size instanceof Array) {
  24266. data = size;
  24267. size = data.length;
  24268. }
  24269. else {
  24270. size = size;
  24271. data = [];
  24272. // Fill with zeros
  24273. for (var i = 0; i < size; i++) {
  24274. data.push(0);
  24275. }
  24276. }
  24277. this._fillAlignment(size);
  24278. this._uniformSizes[name] = size;
  24279. this._uniformLocations[name] = this._uniformLocationPointer;
  24280. this._uniformLocationPointer += size;
  24281. for (var i = 0; i < size; i++) {
  24282. this._data.push(data[i]);
  24283. }
  24284. this._needSync = true;
  24285. };
  24286. /**
  24287. * Wrapper for addUniform.
  24288. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24289. * @param {Matrix} mat A 4x4 matrix.
  24290. */
  24291. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24292. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24293. };
  24294. /**
  24295. * Wrapper for addUniform.
  24296. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24297. * @param {number} x
  24298. * @param {number} y
  24299. */
  24300. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24301. var temp = [x, y];
  24302. this.addUniform(name, temp);
  24303. };
  24304. /**
  24305. * Wrapper for addUniform.
  24306. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24307. * @param {number} x
  24308. * @param {number} y
  24309. * @param {number} z
  24310. */
  24311. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24312. var temp = [x, y, z];
  24313. this.addUniform(name, temp);
  24314. };
  24315. /**
  24316. * Wrapper for addUniform.
  24317. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24318. * @param {Color3} color
  24319. */
  24320. UniformBuffer.prototype.addColor3 = function (name, color) {
  24321. var temp = [];
  24322. color.toArray(temp);
  24323. this.addUniform(name, temp);
  24324. };
  24325. /**
  24326. * Wrapper for addUniform.
  24327. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24328. * @param {Color3} color
  24329. * @param {number} alpha
  24330. */
  24331. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24332. var temp = [];
  24333. color.toArray(temp);
  24334. temp.push(alpha);
  24335. this.addUniform(name, temp);
  24336. };
  24337. /**
  24338. * Wrapper for addUniform.
  24339. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24340. * @param {Vector3} vector
  24341. */
  24342. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24343. var temp = [];
  24344. vector.toArray(temp);
  24345. this.addUniform(name, temp);
  24346. };
  24347. /**
  24348. * Wrapper for addUniform.
  24349. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24350. */
  24351. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24352. this.addUniform(name, 12);
  24353. };
  24354. /**
  24355. * Wrapper for addUniform.
  24356. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24357. */
  24358. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24359. this.addUniform(name, 8);
  24360. };
  24361. /**
  24362. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24363. */
  24364. UniformBuffer.prototype.create = function () {
  24365. if (this._noUBO) {
  24366. return;
  24367. }
  24368. if (this._buffer) {
  24369. return; // nothing to do
  24370. }
  24371. // See spec, alignment must be filled as a vec4
  24372. this._fillAlignment(4);
  24373. this._bufferData = new Float32Array(this._data);
  24374. if (this._dynamic) {
  24375. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24376. }
  24377. else {
  24378. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24379. }
  24380. this._needSync = true;
  24381. };
  24382. /**
  24383. * Updates the WebGL Uniform Buffer on the GPU.
  24384. * If the `dynamic` flag is set to true, no cache comparison is done.
  24385. * Otherwise, the buffer will be updated only if the cache differs.
  24386. */
  24387. UniformBuffer.prototype.update = function () {
  24388. if (!this._buffer) {
  24389. this.create();
  24390. return;
  24391. }
  24392. if (!this._dynamic && !this._needSync) {
  24393. return;
  24394. }
  24395. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24396. this._needSync = false;
  24397. };
  24398. /**
  24399. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24400. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24401. * @param {number[]|Float32Array} data Flattened data
  24402. * @param {number} size Size of the data.
  24403. */
  24404. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24405. var location = this._uniformLocations[uniformName];
  24406. if (location === undefined) {
  24407. if (this._buffer) {
  24408. // Cannot add an uniform if the buffer is already created
  24409. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24410. return;
  24411. }
  24412. this.addUniform(uniformName, size);
  24413. location = this._uniformLocations[uniformName];
  24414. }
  24415. if (!this._buffer) {
  24416. this.create();
  24417. }
  24418. if (!this._dynamic) {
  24419. // Cache for static uniform buffers
  24420. var changed = false;
  24421. for (var i = 0; i < size; i++) {
  24422. if (this._bufferData[location + i] !== data[i]) {
  24423. changed = true;
  24424. this._bufferData[location + i] = data[i];
  24425. }
  24426. }
  24427. this._needSync = this._needSync || changed;
  24428. }
  24429. else {
  24430. // No cache for dynamic
  24431. for (var i = 0; i < size; i++) {
  24432. this._bufferData[location + i] = data[i];
  24433. }
  24434. }
  24435. };
  24436. // Update methods
  24437. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24438. // To match std140, matrix must be realigned
  24439. for (var i = 0; i < 3; i++) {
  24440. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24441. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24442. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24443. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24444. }
  24445. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24446. };
  24447. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24448. this._currentEffect.setMatrix3x3(name, matrix);
  24449. };
  24450. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24451. this._currentEffect.setMatrix2x2(name, matrix);
  24452. };
  24453. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24454. // To match std140, matrix must be realigned
  24455. for (var i = 0; i < 2; i++) {
  24456. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24457. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24458. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24459. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24460. }
  24461. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24462. };
  24463. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24464. this._currentEffect.setFloat(name, x);
  24465. };
  24466. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24467. UniformBuffer._tempBuffer[0] = x;
  24468. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24469. };
  24470. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y) {
  24471. this._currentEffect.setFloat2(name, x, y);
  24472. };
  24473. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y) {
  24474. UniformBuffer._tempBuffer[0] = x;
  24475. UniformBuffer._tempBuffer[1] = y;
  24476. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24477. };
  24478. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24479. if (suffix === void 0) { suffix = ""; }
  24480. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24481. };
  24482. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24483. if (suffix === void 0) { suffix = ""; }
  24484. UniformBuffer._tempBuffer[0] = x;
  24485. UniformBuffer._tempBuffer[1] = y;
  24486. UniformBuffer._tempBuffer[2] = z;
  24487. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24488. };
  24489. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24490. if (suffix === void 0) { suffix = ""; }
  24491. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24492. };
  24493. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24494. if (suffix === void 0) { suffix = ""; }
  24495. UniformBuffer._tempBuffer[0] = x;
  24496. UniformBuffer._tempBuffer[1] = y;
  24497. UniformBuffer._tempBuffer[2] = z;
  24498. UniformBuffer._tempBuffer[3] = w;
  24499. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24500. };
  24501. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24502. this._currentEffect.setMatrix(name, mat);
  24503. };
  24504. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24505. this.updateUniform(name, mat.toArray(), 16);
  24506. };
  24507. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24508. this._currentEffect.setVector3(name, vector);
  24509. };
  24510. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24511. vector.toArray(UniformBuffer._tempBuffer);
  24512. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24513. };
  24514. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24515. this._currentEffect.setVector4(name, vector);
  24516. };
  24517. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24518. vector.toArray(UniformBuffer._tempBuffer);
  24519. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24520. };
  24521. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24522. if (suffix === void 0) { suffix = ""; }
  24523. this._currentEffect.setColor3(name + suffix, color);
  24524. };
  24525. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24526. if (suffix === void 0) { suffix = ""; }
  24527. color.toArray(UniformBuffer._tempBuffer);
  24528. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24529. };
  24530. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24531. if (suffix === void 0) { suffix = ""; }
  24532. this._currentEffect.setColor4(name + suffix, color, alpha);
  24533. };
  24534. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24535. if (suffix === void 0) { suffix = ""; }
  24536. color.toArray(UniformBuffer._tempBuffer);
  24537. UniformBuffer._tempBuffer[3] = alpha;
  24538. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24539. };
  24540. /**
  24541. * Sets a sampler uniform on the effect.
  24542. * @param {string} name Name of the sampler.
  24543. * @param {Texture} texture
  24544. */
  24545. UniformBuffer.prototype.setTexture = function (name, texture) {
  24546. this._currentEffect.setTexture(name, texture);
  24547. };
  24548. /**
  24549. * Directly updates the value of the uniform in the cache AND on the GPU.
  24550. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24551. * @param {number[]|Float32Array} data Flattened data
  24552. */
  24553. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24554. this.updateUniform(uniformName, data, data.length);
  24555. this.update();
  24556. };
  24557. /**
  24558. * Binds this uniform buffer to an effect.
  24559. * @param {Effect} effect
  24560. * @param {string} name Name of the uniform block in the shader.
  24561. */
  24562. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24563. this._currentEffect = effect;
  24564. if (this._noUBO) {
  24565. return;
  24566. }
  24567. effect.bindUniformBuffer(this._buffer, name);
  24568. };
  24569. /**
  24570. * Disposes the uniform buffer.
  24571. */
  24572. UniformBuffer.prototype.dispose = function () {
  24573. if (!this._buffer) {
  24574. return;
  24575. }
  24576. if (this._engine._releaseBuffer(this._buffer)) {
  24577. this._buffer = null;
  24578. }
  24579. };
  24580. return UniformBuffer;
  24581. }());
  24582. // Pool for avoiding memory leaks
  24583. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24584. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24585. BABYLON.UniformBuffer = UniformBuffer;
  24586. })(BABYLON || (BABYLON = {}));
  24587. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24588. var BABYLON;
  24589. (function (BABYLON) {
  24590. var PushMaterial = (function (_super) {
  24591. __extends(PushMaterial, _super);
  24592. function PushMaterial(name, scene) {
  24593. var _this = _super.call(this, name, scene) || this;
  24594. _this.storeEffectOnSubMeshes = true;
  24595. return _this;
  24596. }
  24597. PushMaterial.prototype.getEffect = function () {
  24598. return this._activeEffect;
  24599. };
  24600. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24601. if (!mesh) {
  24602. return false;
  24603. }
  24604. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24605. return true;
  24606. }
  24607. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24608. };
  24609. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24610. this._activeEffect.setMatrix("world", world);
  24611. };
  24612. PushMaterial.prototype.bind = function (world, mesh) {
  24613. if (!mesh) {
  24614. return;
  24615. }
  24616. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24617. };
  24618. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24619. _super.prototype._afterBind.call(this, mesh);
  24620. this.getScene()._cachedEffect = effect;
  24621. };
  24622. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24623. if (visibility === void 0) { visibility = 0; }
  24624. return scene.isCachedMaterialValid(this, effect, visibility);
  24625. };
  24626. PushMaterial.prototype.markAsDirty = function (flag) {
  24627. if (flag & BABYLON.Material.TextureDirtyFlag) {
  24628. this._markAllSubMeshesAsTexturesDirty();
  24629. }
  24630. if (flag & BABYLON.Material.LightDirtyFlag) {
  24631. this._markAllSubMeshesAsLightsDirty();
  24632. }
  24633. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  24634. this._markAllSubMeshesAsFresnelDirty();
  24635. }
  24636. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  24637. this._markAllSubMeshesAsAttributesDirty();
  24638. }
  24639. if (flag & BABYLON.Material.MiscDirtyFlag) {
  24640. this._markAllSubMeshesAsMiscDirty();
  24641. }
  24642. this.getScene().resetCachedMaterial();
  24643. };
  24644. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  24645. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24646. var mesh = _a[_i];
  24647. if (!mesh.subMeshes) {
  24648. continue;
  24649. }
  24650. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24651. var subMesh = _c[_b];
  24652. if (subMesh.getMaterial() !== this) {
  24653. continue;
  24654. }
  24655. if (!subMesh._materialDefines) {
  24656. return;
  24657. }
  24658. func(subMesh._materialDefines);
  24659. }
  24660. }
  24661. };
  24662. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24663. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24664. };
  24665. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24666. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24667. };
  24668. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  24669. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24670. };
  24671. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24672. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24673. };
  24674. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  24675. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24676. };
  24677. return PushMaterial;
  24678. }(BABYLON.Material));
  24679. BABYLON.PushMaterial = PushMaterial;
  24680. })(BABYLON || (BABYLON = {}));
  24681. //# sourceMappingURL=babylon.pushMaterial.js.map
  24682. var BABYLON;
  24683. (function (BABYLON) {
  24684. var VertexData = (function () {
  24685. function VertexData() {
  24686. }
  24687. VertexData.prototype.set = function (data, kind) {
  24688. switch (kind) {
  24689. case BABYLON.VertexBuffer.PositionKind:
  24690. this.positions = data;
  24691. break;
  24692. case BABYLON.VertexBuffer.NormalKind:
  24693. this.normals = data;
  24694. break;
  24695. case BABYLON.VertexBuffer.TangentKind:
  24696. this.tangents = data;
  24697. break;
  24698. case BABYLON.VertexBuffer.UVKind:
  24699. this.uvs = data;
  24700. break;
  24701. case BABYLON.VertexBuffer.UV2Kind:
  24702. this.uvs2 = data;
  24703. break;
  24704. case BABYLON.VertexBuffer.UV3Kind:
  24705. this.uvs3 = data;
  24706. break;
  24707. case BABYLON.VertexBuffer.UV4Kind:
  24708. this.uvs4 = data;
  24709. break;
  24710. case BABYLON.VertexBuffer.UV5Kind:
  24711. this.uvs5 = data;
  24712. break;
  24713. case BABYLON.VertexBuffer.UV6Kind:
  24714. this.uvs6 = data;
  24715. break;
  24716. case BABYLON.VertexBuffer.ColorKind:
  24717. this.colors = data;
  24718. break;
  24719. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24720. this.matricesIndices = data;
  24721. break;
  24722. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24723. this.matricesWeights = data;
  24724. break;
  24725. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24726. this.matricesIndicesExtra = data;
  24727. break;
  24728. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24729. this.matricesWeightsExtra = data;
  24730. break;
  24731. }
  24732. };
  24733. /**
  24734. * Associates the vertexData to the passed Mesh.
  24735. * Sets it as updatable or not (default `false`).
  24736. * Returns the VertexData.
  24737. */
  24738. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24739. this._applyTo(mesh, updatable);
  24740. return this;
  24741. };
  24742. /**
  24743. * Associates the vertexData to the passed Geometry.
  24744. * Sets it as updatable or not (default `false`).
  24745. * Returns the VertexData.
  24746. */
  24747. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24748. this._applyTo(geometry, updatable);
  24749. return this;
  24750. };
  24751. /**
  24752. * Updates the associated mesh.
  24753. * Returns the VertexData.
  24754. */
  24755. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24756. this._update(mesh);
  24757. return this;
  24758. };
  24759. /**
  24760. * Updates the associated geometry.
  24761. * Returns the VertexData.
  24762. */
  24763. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24764. this._update(geometry);
  24765. return this;
  24766. };
  24767. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24768. if (this.positions) {
  24769. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24770. }
  24771. if (this.normals) {
  24772. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24773. }
  24774. if (this.tangents) {
  24775. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  24776. }
  24777. if (this.uvs) {
  24778. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24779. }
  24780. if (this.uvs2) {
  24781. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24782. }
  24783. if (this.uvs3) {
  24784. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24785. }
  24786. if (this.uvs4) {
  24787. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24788. }
  24789. if (this.uvs5) {
  24790. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24791. }
  24792. if (this.uvs6) {
  24793. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24794. }
  24795. if (this.colors) {
  24796. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24797. }
  24798. if (this.matricesIndices) {
  24799. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24800. }
  24801. if (this.matricesWeights) {
  24802. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24803. }
  24804. if (this.matricesIndicesExtra) {
  24805. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24806. }
  24807. if (this.matricesWeightsExtra) {
  24808. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24809. }
  24810. if (this.indices) {
  24811. meshOrGeometry.setIndices(this.indices);
  24812. }
  24813. return this;
  24814. };
  24815. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24816. if (this.positions) {
  24817. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24818. }
  24819. if (this.normals) {
  24820. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24821. }
  24822. if (this.tangents) {
  24823. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  24824. }
  24825. if (this.uvs) {
  24826. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24827. }
  24828. if (this.uvs2) {
  24829. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24830. }
  24831. if (this.uvs3) {
  24832. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24833. }
  24834. if (this.uvs4) {
  24835. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24836. }
  24837. if (this.uvs5) {
  24838. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24839. }
  24840. if (this.uvs6) {
  24841. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24842. }
  24843. if (this.colors) {
  24844. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24845. }
  24846. if (this.matricesIndices) {
  24847. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24848. }
  24849. if (this.matricesWeights) {
  24850. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24851. }
  24852. if (this.matricesIndicesExtra) {
  24853. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24854. }
  24855. if (this.matricesWeightsExtra) {
  24856. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24857. }
  24858. if (this.indices) {
  24859. meshOrGeometry.setIndices(this.indices);
  24860. }
  24861. return this;
  24862. };
  24863. /**
  24864. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  24865. * Returns the VertexData.
  24866. */
  24867. VertexData.prototype.transform = function (matrix) {
  24868. var transformed = BABYLON.Vector3.Zero();
  24869. var index;
  24870. if (this.positions) {
  24871. var position = BABYLON.Vector3.Zero();
  24872. for (index = 0; index < this.positions.length; index += 3) {
  24873. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24874. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24875. this.positions[index] = transformed.x;
  24876. this.positions[index + 1] = transformed.y;
  24877. this.positions[index + 2] = transformed.z;
  24878. }
  24879. }
  24880. if (this.normals) {
  24881. var normal = BABYLON.Vector3.Zero();
  24882. for (index = 0; index < this.normals.length; index += 3) {
  24883. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24884. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24885. this.normals[index] = transformed.x;
  24886. this.normals[index + 1] = transformed.y;
  24887. this.normals[index + 2] = transformed.z;
  24888. }
  24889. }
  24890. if (this.tangents) {
  24891. var tangent = BABYLON.Vector4.Zero();
  24892. var tangentTransformed = BABYLON.Vector4.Zero();
  24893. for (index = 0; index < this.tangents.length; index += 4) {
  24894. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  24895. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  24896. this.tangents[index] = tangentTransformed.x;
  24897. this.tangents[index + 1] = tangentTransformed.y;
  24898. this.tangents[index + 2] = tangentTransformed.z;
  24899. this.tangents[index + 3] = tangentTransformed.w;
  24900. }
  24901. }
  24902. return this;
  24903. };
  24904. /**
  24905. * Merges the passed VertexData into the current one.
  24906. * Returns the modified VertexData.
  24907. */
  24908. VertexData.prototype.merge = function (other) {
  24909. if (other.indices) {
  24910. if (!this.indices) {
  24911. this.indices = [];
  24912. }
  24913. var offset = this.positions ? this.positions.length / 3 : 0;
  24914. for (var index = 0; index < other.indices.length; index++) {
  24915. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  24916. this.indices.push(other.indices[index] + offset);
  24917. }
  24918. }
  24919. this.positions = this._mergeElement(this.positions, other.positions);
  24920. this.normals = this._mergeElement(this.normals, other.normals);
  24921. this.tangents = this._mergeElement(this.tangents, other.tangents);
  24922. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24923. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24924. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24925. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24926. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24927. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24928. this.colors = this._mergeElement(this.colors, other.colors);
  24929. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24930. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24931. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24932. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24933. return this;
  24934. };
  24935. VertexData.prototype._mergeElement = function (source, other) {
  24936. if (!other)
  24937. return source;
  24938. if (!source)
  24939. return other;
  24940. var len = other.length + source.length;
  24941. var isSrcTypedArray = source instanceof Float32Array;
  24942. var isOthTypedArray = other instanceof Float32Array;
  24943. // use non-loop method when the source is Float32Array
  24944. if (isSrcTypedArray) {
  24945. var ret32 = new Float32Array(len);
  24946. ret32.set(source);
  24947. ret32.set(other, source.length);
  24948. return ret32;
  24949. // source is number[], when other is also use concat
  24950. }
  24951. else if (!isOthTypedArray) {
  24952. return source.concat(other);
  24953. // source is a number[], but other is a Float32Array, loop required
  24954. }
  24955. else {
  24956. var ret = source.slice(0); // copy source to a separate array
  24957. for (var i = 0, len = other.length; i < len; i++) {
  24958. ret.push(other[i]);
  24959. }
  24960. return ret;
  24961. }
  24962. };
  24963. /**
  24964. * Serializes the VertexData.
  24965. * Returns a serialized object.
  24966. */
  24967. VertexData.prototype.serialize = function () {
  24968. var serializationObject = this.serialize();
  24969. if (this.positions) {
  24970. serializationObject.positions = this.positions;
  24971. }
  24972. if (this.normals) {
  24973. serializationObject.normals = this.normals;
  24974. }
  24975. if (this.tangents) {
  24976. serializationObject.tangents = this.tangents;
  24977. }
  24978. if (this.uvs) {
  24979. serializationObject.uvs = this.uvs;
  24980. }
  24981. if (this.uvs2) {
  24982. serializationObject.uvs2 = this.uvs2;
  24983. }
  24984. if (this.uvs3) {
  24985. serializationObject.uvs3 = this.uvs3;
  24986. }
  24987. if (this.uvs4) {
  24988. serializationObject.uvs4 = this.uvs4;
  24989. }
  24990. if (this.uvs5) {
  24991. serializationObject.uvs5 = this.uvs5;
  24992. }
  24993. if (this.uvs6) {
  24994. serializationObject.uvs6 = this.uvs6;
  24995. }
  24996. if (this.colors) {
  24997. serializationObject.colors = this.colors;
  24998. }
  24999. if (this.matricesIndices) {
  25000. serializationObject.matricesIndices = this.matricesIndices;
  25001. serializationObject.matricesIndices._isExpanded = true;
  25002. }
  25003. if (this.matricesWeights) {
  25004. serializationObject.matricesWeights = this.matricesWeights;
  25005. }
  25006. if (this.matricesIndicesExtra) {
  25007. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25008. serializationObject.matricesIndicesExtra._isExpanded = true;
  25009. }
  25010. if (this.matricesWeightsExtra) {
  25011. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25012. }
  25013. serializationObject.indices = this.indices;
  25014. return serializationObject;
  25015. };
  25016. // Statics
  25017. /**
  25018. * Returns the object VertexData associated to the passed mesh.
  25019. */
  25020. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25021. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25022. };
  25023. /**
  25024. * Returns the object VertexData associated to the passed geometry.
  25025. */
  25026. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25027. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25028. };
  25029. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25030. var result = new VertexData();
  25031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25032. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25033. }
  25034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25035. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25036. }
  25037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25038. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25039. }
  25040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25041. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25042. }
  25043. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25044. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25045. }
  25046. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25047. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25048. }
  25049. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25050. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25051. }
  25052. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25053. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25054. }
  25055. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25056. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25057. }
  25058. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25059. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25060. }
  25061. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25062. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25063. }
  25064. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25065. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25066. }
  25067. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25068. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25069. }
  25070. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25071. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25072. }
  25073. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25074. return result;
  25075. };
  25076. /**
  25077. * Creates the vertexData of the Ribbon.
  25078. */
  25079. VertexData.CreateRibbon = function (options) {
  25080. var pathArray = options.pathArray;
  25081. var closeArray = options.closeArray || false;
  25082. var closePath = options.closePath || false;
  25083. var invertUV = options.invertUV || false;
  25084. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25085. var offset = options.offset || defaultOffset;
  25086. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25087. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25088. var customUV = options.uvs;
  25089. var customColors = options.colors;
  25090. var positions = [];
  25091. var indices = [];
  25092. var normals = [];
  25093. var uvs = [];
  25094. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25095. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25096. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25097. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25098. var minlg; // minimal length among all paths from pathArray
  25099. var lg = []; // array of path lengths : nb of vertex per path
  25100. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25101. var p; // path iterator
  25102. var i; // point iterator
  25103. var j; // point iterator
  25104. // if single path in pathArray
  25105. if (pathArray.length < 2) {
  25106. var ar1 = [];
  25107. var ar2 = [];
  25108. for (i = 0; i < pathArray[0].length - offset; i++) {
  25109. ar1.push(pathArray[0][i]);
  25110. ar2.push(pathArray[0][i + offset]);
  25111. }
  25112. pathArray = [ar1, ar2];
  25113. }
  25114. // positions and horizontal distances (u)
  25115. var idc = 0;
  25116. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25117. var path;
  25118. var l;
  25119. minlg = pathArray[0].length;
  25120. var vectlg;
  25121. var dist;
  25122. for (p = 0; p < pathArray.length; p++) {
  25123. uTotalDistance[p] = 0;
  25124. us[p] = [0];
  25125. path = pathArray[p];
  25126. l = path.length;
  25127. minlg = (minlg < l) ? minlg : l;
  25128. j = 0;
  25129. while (j < l) {
  25130. positions.push(path[j].x, path[j].y, path[j].z);
  25131. if (j > 0) {
  25132. vectlg = path[j].subtract(path[j - 1]).length();
  25133. dist = vectlg + uTotalDistance[p];
  25134. us[p].push(dist);
  25135. uTotalDistance[p] = dist;
  25136. }
  25137. j++;
  25138. }
  25139. if (closePath) {
  25140. j--;
  25141. positions.push(path[0].x, path[0].y, path[0].z);
  25142. vectlg = path[j].subtract(path[0]).length();
  25143. dist = vectlg + uTotalDistance[p];
  25144. us[p].push(dist);
  25145. uTotalDistance[p] = dist;
  25146. }
  25147. lg[p] = l + closePathCorr;
  25148. idx[p] = idc;
  25149. idc += (l + closePathCorr);
  25150. }
  25151. // vertical distances (v)
  25152. var path1;
  25153. var path2;
  25154. var vertex1;
  25155. var vertex2;
  25156. for (i = 0; i < minlg + closePathCorr; i++) {
  25157. vTotalDistance[i] = 0;
  25158. vs[i] = [0];
  25159. for (p = 0; p < pathArray.length - 1; p++) {
  25160. path1 = pathArray[p];
  25161. path2 = pathArray[p + 1];
  25162. if (i === minlg) {
  25163. vertex1 = path1[0];
  25164. vertex2 = path2[0];
  25165. }
  25166. else {
  25167. vertex1 = path1[i];
  25168. vertex2 = path2[i];
  25169. }
  25170. vectlg = vertex2.subtract(vertex1).length();
  25171. dist = vectlg + vTotalDistance[i];
  25172. vs[i].push(dist);
  25173. vTotalDistance[i] = dist;
  25174. }
  25175. if (closeArray) {
  25176. path1 = pathArray[p];
  25177. path2 = pathArray[0];
  25178. if (i === minlg) {
  25179. vertex2 = path2[0];
  25180. }
  25181. vectlg = vertex2.subtract(vertex1).length();
  25182. dist = vectlg + vTotalDistance[i];
  25183. vTotalDistance[i] = dist;
  25184. }
  25185. }
  25186. // uvs
  25187. var u;
  25188. var v;
  25189. if (customUV) {
  25190. for (p = 0; p < customUV.length; p++) {
  25191. uvs.push(customUV[p].x, customUV[p].y);
  25192. }
  25193. }
  25194. else {
  25195. for (p = 0; p < pathArray.length; p++) {
  25196. for (i = 0; i < minlg + closePathCorr; i++) {
  25197. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25198. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25199. if (invertUV) {
  25200. uvs.push(v, u);
  25201. }
  25202. else {
  25203. uvs.push(u, v);
  25204. }
  25205. }
  25206. }
  25207. }
  25208. // indices
  25209. p = 0; // path index
  25210. var pi = 0; // positions array index
  25211. var l1 = lg[p] - 1; // path1 length
  25212. var l2 = lg[p + 1] - 1; // path2 length
  25213. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25214. var shft = idx[1] - idx[0]; // shift
  25215. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25216. while (pi <= min && p < path1nb) {
  25217. // 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
  25218. indices.push(pi, pi + shft, pi + 1);
  25219. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25220. pi += 1;
  25221. if (pi === min) {
  25222. p++;
  25223. if (p === lg.length - 1) {
  25224. shft = idx[0] - idx[p];
  25225. l1 = lg[p] - 1;
  25226. l2 = lg[0] - 1;
  25227. }
  25228. else {
  25229. shft = idx[p + 1] - idx[p];
  25230. l1 = lg[p] - 1;
  25231. l2 = lg[p + 1] - 1;
  25232. }
  25233. pi = idx[p];
  25234. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25235. }
  25236. }
  25237. // normals
  25238. VertexData.ComputeNormals(positions, indices, normals);
  25239. if (closePath) {
  25240. var indexFirst = 0;
  25241. var indexLast = 0;
  25242. for (p = 0; p < pathArray.length; p++) {
  25243. indexFirst = idx[p] * 3;
  25244. if (p + 1 < pathArray.length) {
  25245. indexLast = (idx[p + 1] - 1) * 3;
  25246. }
  25247. else {
  25248. indexLast = normals.length - 3;
  25249. }
  25250. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25251. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25252. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25253. normals[indexLast] = normals[indexFirst];
  25254. normals[indexLast + 1] = normals[indexFirst + 1];
  25255. normals[indexLast + 2] = normals[indexFirst + 2];
  25256. }
  25257. }
  25258. // sides
  25259. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25260. // Colors
  25261. if (customColors) {
  25262. var colors = new Float32Array(customColors.length * 4);
  25263. for (var c = 0; c < customColors.length; c++) {
  25264. colors[c * 4] = customColors[c].r;
  25265. colors[c * 4 + 1] = customColors[c].g;
  25266. colors[c * 4 + 2] = customColors[c].b;
  25267. colors[c * 4 + 3] = customColors[c].a;
  25268. }
  25269. }
  25270. // Result
  25271. var vertexData = new VertexData();
  25272. var positions32 = new Float32Array(positions);
  25273. var normals32 = new Float32Array(normals);
  25274. var uvs32 = new Float32Array(uvs);
  25275. vertexData.indices = indices;
  25276. vertexData.positions = positions32;
  25277. vertexData.normals = normals32;
  25278. vertexData.uvs = uvs32;
  25279. if (customColors) {
  25280. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25281. }
  25282. if (closePath) {
  25283. vertexData._idx = idx;
  25284. }
  25285. return vertexData;
  25286. };
  25287. /**
  25288. * Creates the VertexData of the Box.
  25289. */
  25290. VertexData.CreateBox = function (options) {
  25291. var normalsSource = [
  25292. new BABYLON.Vector3(0, 0, 1),
  25293. new BABYLON.Vector3(0, 0, -1),
  25294. new BABYLON.Vector3(1, 0, 0),
  25295. new BABYLON.Vector3(-1, 0, 0),
  25296. new BABYLON.Vector3(0, 1, 0),
  25297. new BABYLON.Vector3(0, -1, 0)
  25298. ];
  25299. var indices = [];
  25300. var positions = [];
  25301. var normals = [];
  25302. var uvs = [];
  25303. var width = options.width || options.size || 1;
  25304. var height = options.height || options.size || 1;
  25305. var depth = options.depth || options.size || 1;
  25306. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25307. var faceUV = options.faceUV || new Array(6);
  25308. var faceColors = options.faceColors;
  25309. var colors = [];
  25310. // default face colors and UV if undefined
  25311. for (var f = 0; f < 6; f++) {
  25312. if (faceUV[f] === undefined) {
  25313. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25314. }
  25315. if (faceColors && faceColors[f] === undefined) {
  25316. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25317. }
  25318. }
  25319. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25320. // Create each face in turn.
  25321. for (var index = 0; index < normalsSource.length; index++) {
  25322. var normal = normalsSource[index];
  25323. // Get two vectors perpendicular to the face normal and to each other.
  25324. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25325. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25326. // Six indices (two triangles) per face.
  25327. var verticesLength = positions.length / 3;
  25328. indices.push(verticesLength);
  25329. indices.push(verticesLength + 1);
  25330. indices.push(verticesLength + 2);
  25331. indices.push(verticesLength);
  25332. indices.push(verticesLength + 2);
  25333. indices.push(verticesLength + 3);
  25334. // Four vertices per face.
  25335. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25336. positions.push(vertex.x, vertex.y, vertex.z);
  25337. normals.push(normal.x, normal.y, normal.z);
  25338. uvs.push(faceUV[index].z, faceUV[index].w);
  25339. if (faceColors) {
  25340. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25341. }
  25342. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25343. positions.push(vertex.x, vertex.y, vertex.z);
  25344. normals.push(normal.x, normal.y, normal.z);
  25345. uvs.push(faceUV[index].x, faceUV[index].w);
  25346. if (faceColors) {
  25347. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25348. }
  25349. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25350. positions.push(vertex.x, vertex.y, vertex.z);
  25351. normals.push(normal.x, normal.y, normal.z);
  25352. uvs.push(faceUV[index].x, faceUV[index].y);
  25353. if (faceColors) {
  25354. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25355. }
  25356. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25357. positions.push(vertex.x, vertex.y, vertex.z);
  25358. normals.push(normal.x, normal.y, normal.z);
  25359. uvs.push(faceUV[index].z, faceUV[index].y);
  25360. if (faceColors) {
  25361. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25362. }
  25363. }
  25364. // sides
  25365. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25366. // Result
  25367. var vertexData = new VertexData();
  25368. vertexData.indices = indices;
  25369. vertexData.positions = positions;
  25370. vertexData.normals = normals;
  25371. vertexData.uvs = uvs;
  25372. if (faceColors) {
  25373. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25374. vertexData.colors = totalColors;
  25375. }
  25376. return vertexData;
  25377. };
  25378. /**
  25379. * Creates the VertexData of the Sphere.
  25380. */
  25381. VertexData.CreateSphere = function (options) {
  25382. var segments = options.segments || 32;
  25383. var diameterX = options.diameterX || options.diameter || 1;
  25384. var diameterY = options.diameterY || options.diameter || 1;
  25385. var diameterZ = options.diameterZ || options.diameter || 1;
  25386. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25387. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25388. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25389. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25390. var totalZRotationSteps = 2 + segments;
  25391. var totalYRotationSteps = 2 * totalZRotationSteps;
  25392. var indices = [];
  25393. var positions = [];
  25394. var normals = [];
  25395. var uvs = [];
  25396. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25397. var normalizedZ = zRotationStep / totalZRotationSteps;
  25398. var angleZ = normalizedZ * Math.PI * slice;
  25399. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25400. var normalizedY = yRotationStep / totalYRotationSteps;
  25401. var angleY = normalizedY * Math.PI * 2 * arc;
  25402. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25403. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25404. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25405. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25406. var vertex = complete.multiply(radius);
  25407. var normal = complete.divide(radius).normalize();
  25408. positions.push(vertex.x, vertex.y, vertex.z);
  25409. normals.push(normal.x, normal.y, normal.z);
  25410. uvs.push(normalizedY, normalizedZ);
  25411. }
  25412. if (zRotationStep > 0) {
  25413. var verticesCount = positions.length / 3;
  25414. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25415. indices.push((firstIndex));
  25416. indices.push((firstIndex + 1));
  25417. indices.push(firstIndex + totalYRotationSteps + 1);
  25418. indices.push((firstIndex + totalYRotationSteps + 1));
  25419. indices.push((firstIndex + 1));
  25420. indices.push((firstIndex + totalYRotationSteps + 2));
  25421. }
  25422. }
  25423. }
  25424. // Sides
  25425. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25426. // Result
  25427. var vertexData = new VertexData();
  25428. vertexData.indices = indices;
  25429. vertexData.positions = positions;
  25430. vertexData.normals = normals;
  25431. vertexData.uvs = uvs;
  25432. return vertexData;
  25433. };
  25434. /**
  25435. * Creates the VertexData of the Cylinder or Cone.
  25436. */
  25437. VertexData.CreateCylinder = function (options) {
  25438. var height = options.height || 2;
  25439. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25440. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25441. var tessellation = options.tessellation || 24;
  25442. var subdivisions = options.subdivisions || 1;
  25443. var hasRings = options.hasRings;
  25444. var enclose = options.enclose;
  25445. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25446. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25447. var faceUV = options.faceUV || new Array(3);
  25448. var faceColors = options.faceColors;
  25449. // default face colors and UV if undefined
  25450. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25451. var ringNb = (hasRings) ? subdivisions : 1;
  25452. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25453. var f;
  25454. for (f = 0; f < surfaceNb; f++) {
  25455. if (faceColors && faceColors[f] === undefined) {
  25456. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25457. }
  25458. }
  25459. for (f = 0; f < surfaceNb; f++) {
  25460. if (faceUV && faceUV[f] === undefined) {
  25461. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25462. }
  25463. }
  25464. var indices = [];
  25465. var positions = [];
  25466. var normals = [];
  25467. var uvs = [];
  25468. var colors = [];
  25469. var angle_step = Math.PI * 2 * arc / tessellation;
  25470. var angle;
  25471. var h;
  25472. var radius;
  25473. var tan = (diameterBottom - diameterTop) / 2 / height;
  25474. var ringVertex = BABYLON.Vector3.Zero();
  25475. var ringNormal = BABYLON.Vector3.Zero();
  25476. var ringFirstVertex = BABYLON.Vector3.Zero();
  25477. var ringFirstNormal = BABYLON.Vector3.Zero();
  25478. var quadNormal = BABYLON.Vector3.Zero();
  25479. var Y = BABYLON.Axis.Y;
  25480. // positions, normals, uvs
  25481. var i;
  25482. var j;
  25483. var r;
  25484. var ringIdx = 1;
  25485. var s = 1; // surface index
  25486. var cs = 0;
  25487. var v = 0;
  25488. for (i = 0; i <= subdivisions; i++) {
  25489. h = i / subdivisions;
  25490. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25491. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25492. for (r = 0; r < ringIdx; r++) {
  25493. if (hasRings) {
  25494. s += r;
  25495. }
  25496. if (enclose) {
  25497. s += 2 * r;
  25498. }
  25499. for (j = 0; j <= tessellation; j++) {
  25500. angle = j * angle_step;
  25501. // position
  25502. ringVertex.x = Math.cos(-angle) * radius;
  25503. ringVertex.y = -height / 2 + h * height;
  25504. ringVertex.z = Math.sin(-angle) * radius;
  25505. // normal
  25506. if (diameterTop === 0 && i === subdivisions) {
  25507. // if no top cap, reuse former normals
  25508. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25509. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25510. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25511. }
  25512. else {
  25513. ringNormal.x = ringVertex.x;
  25514. ringNormal.z = ringVertex.z;
  25515. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25516. ringNormal.normalize();
  25517. }
  25518. // keep first ring vertex values for enclose
  25519. if (j === 0) {
  25520. ringFirstVertex.copyFrom(ringVertex);
  25521. ringFirstNormal.copyFrom(ringNormal);
  25522. }
  25523. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25524. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25525. if (hasRings) {
  25526. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25527. }
  25528. else {
  25529. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25530. }
  25531. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25532. if (faceColors) {
  25533. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25534. }
  25535. }
  25536. // if enclose, add four vertices and their dedicated normals
  25537. if (arc !== 1 && enclose) {
  25538. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25539. positions.push(0, ringVertex.y, 0);
  25540. positions.push(0, ringVertex.y, 0);
  25541. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25542. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25543. quadNormal.normalize();
  25544. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25545. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25546. quadNormal.normalize();
  25547. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25548. if (hasRings) {
  25549. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25550. }
  25551. else {
  25552. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25553. }
  25554. uvs.push(faceUV[s + 1].x, v);
  25555. uvs.push(faceUV[s + 1].z, v);
  25556. if (hasRings) {
  25557. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25558. }
  25559. else {
  25560. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25561. }
  25562. uvs.push(faceUV[s + 2].x, v);
  25563. uvs.push(faceUV[s + 2].z, v);
  25564. if (faceColors) {
  25565. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25566. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25567. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25568. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25569. }
  25570. }
  25571. if (cs !== s) {
  25572. cs = s;
  25573. }
  25574. }
  25575. }
  25576. // indices
  25577. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25578. var s;
  25579. i = 0;
  25580. for (s = 0; s < subdivisions; s++) {
  25581. for (j = 0; j < tessellation; j++) {
  25582. var i0 = i * (e + 1) + j;
  25583. var i1 = (i + 1) * (e + 1) + j;
  25584. var i2 = i * (e + 1) + (j + 1);
  25585. var i3 = (i + 1) * (e + 1) + (j + 1);
  25586. indices.push(i0, i1, i2);
  25587. indices.push(i3, i2, i1);
  25588. }
  25589. if (arc !== 1 && enclose) {
  25590. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25591. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25592. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25593. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25594. }
  25595. i = (hasRings) ? (i + 2) : (i + 1);
  25596. }
  25597. // Caps
  25598. var createCylinderCap = function (isTop) {
  25599. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25600. if (radius === 0) {
  25601. return;
  25602. }
  25603. // Cap positions, normals & uvs
  25604. var angle;
  25605. var circleVector;
  25606. var i;
  25607. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25608. var c;
  25609. if (faceColors) {
  25610. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25611. }
  25612. // cap center
  25613. var vbase = positions.length / 3;
  25614. var offset = isTop ? height / 2 : -height / 2;
  25615. var center = new BABYLON.Vector3(0, offset, 0);
  25616. positions.push(center.x, center.y, center.z);
  25617. normals.push(0, isTop ? 1 : -1, 0);
  25618. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25619. if (faceColors) {
  25620. colors.push(c.r, c.g, c.b, c.a);
  25621. }
  25622. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25623. for (i = 0; i <= tessellation; i++) {
  25624. angle = Math.PI * 2 * i * arc / tessellation;
  25625. var cos = Math.cos(-angle);
  25626. var sin = Math.sin(-angle);
  25627. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25628. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25629. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25630. normals.push(0, isTop ? 1 : -1, 0);
  25631. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25632. if (faceColors) {
  25633. colors.push(c.r, c.g, c.b, c.a);
  25634. }
  25635. }
  25636. // Cap indices
  25637. for (i = 0; i < tessellation; i++) {
  25638. if (!isTop) {
  25639. indices.push(vbase);
  25640. indices.push(vbase + (i + 1));
  25641. indices.push(vbase + (i + 2));
  25642. }
  25643. else {
  25644. indices.push(vbase);
  25645. indices.push(vbase + (i + 2));
  25646. indices.push(vbase + (i + 1));
  25647. }
  25648. }
  25649. };
  25650. // add caps to geometry
  25651. createCylinderCap(false);
  25652. createCylinderCap(true);
  25653. // Sides
  25654. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25655. var vertexData = new VertexData();
  25656. vertexData.indices = indices;
  25657. vertexData.positions = positions;
  25658. vertexData.normals = normals;
  25659. vertexData.uvs = uvs;
  25660. if (faceColors) {
  25661. vertexData.colors = colors;
  25662. }
  25663. return vertexData;
  25664. };
  25665. /**
  25666. * Creates the VertexData of the Torus.
  25667. */
  25668. VertexData.CreateTorus = function (options) {
  25669. var indices = [];
  25670. var positions = [];
  25671. var normals = [];
  25672. var uvs = [];
  25673. var diameter = options.diameter || 1;
  25674. var thickness = options.thickness || 0.5;
  25675. var tessellation = options.tessellation || 16;
  25676. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25677. var stride = tessellation + 1;
  25678. for (var i = 0; i <= tessellation; i++) {
  25679. var u = i / tessellation;
  25680. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25681. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25682. for (var j = 0; j <= tessellation; j++) {
  25683. var v = 1 - j / tessellation;
  25684. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25685. var dx = Math.cos(innerAngle);
  25686. var dy = Math.sin(innerAngle);
  25687. // Create a vertex.
  25688. var normal = new BABYLON.Vector3(dx, dy, 0);
  25689. var position = normal.scale(thickness / 2);
  25690. var textureCoordinate = new BABYLON.Vector2(u, v);
  25691. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25692. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25693. positions.push(position.x, position.y, position.z);
  25694. normals.push(normal.x, normal.y, normal.z);
  25695. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25696. // And create indices for two triangles.
  25697. var nextI = (i + 1) % stride;
  25698. var nextJ = (j + 1) % stride;
  25699. indices.push(i * stride + j);
  25700. indices.push(i * stride + nextJ);
  25701. indices.push(nextI * stride + j);
  25702. indices.push(i * stride + nextJ);
  25703. indices.push(nextI * stride + nextJ);
  25704. indices.push(nextI * stride + j);
  25705. }
  25706. }
  25707. // Sides
  25708. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25709. // Result
  25710. var vertexData = new VertexData();
  25711. vertexData.indices = indices;
  25712. vertexData.positions = positions;
  25713. vertexData.normals = normals;
  25714. vertexData.uvs = uvs;
  25715. return vertexData;
  25716. };
  25717. /**
  25718. * Creates the VertexData of the LineSystem.
  25719. */
  25720. VertexData.CreateLineSystem = function (options) {
  25721. var indices = [];
  25722. var positions = [];
  25723. var lines = options.lines;
  25724. var idx = 0;
  25725. for (var l = 0; l < lines.length; l++) {
  25726. var points = lines[l];
  25727. for (var index = 0; index < points.length; index++) {
  25728. positions.push(points[index].x, points[index].y, points[index].z);
  25729. if (index > 0) {
  25730. indices.push(idx - 1);
  25731. indices.push(idx);
  25732. }
  25733. idx++;
  25734. }
  25735. }
  25736. var vertexData = new VertexData();
  25737. vertexData.indices = indices;
  25738. vertexData.positions = positions;
  25739. return vertexData;
  25740. };
  25741. /**
  25742. * Create the VertexData of the DashedLines.
  25743. */
  25744. VertexData.CreateDashedLines = function (options) {
  25745. var dashSize = options.dashSize || 3;
  25746. var gapSize = options.gapSize || 1;
  25747. var dashNb = options.dashNb || 200;
  25748. var points = options.points;
  25749. var positions = new Array();
  25750. var indices = new Array();
  25751. var curvect = BABYLON.Vector3.Zero();
  25752. var lg = 0;
  25753. var nb = 0;
  25754. var shft = 0;
  25755. var dashshft = 0;
  25756. var curshft = 0;
  25757. var idx = 0;
  25758. var i = 0;
  25759. for (i = 0; i < points.length - 1; i++) {
  25760. points[i + 1].subtractToRef(points[i], curvect);
  25761. lg += curvect.length();
  25762. }
  25763. shft = lg / dashNb;
  25764. dashshft = dashSize * shft / (dashSize + gapSize);
  25765. for (i = 0; i < points.length - 1; i++) {
  25766. points[i + 1].subtractToRef(points[i], curvect);
  25767. nb = Math.floor(curvect.length() / shft);
  25768. curvect.normalize();
  25769. for (var j = 0; j < nb; j++) {
  25770. curshft = shft * j;
  25771. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25772. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25773. indices.push(idx, idx + 1);
  25774. idx += 2;
  25775. }
  25776. }
  25777. // Result
  25778. var vertexData = new VertexData();
  25779. vertexData.positions = positions;
  25780. vertexData.indices = indices;
  25781. return vertexData;
  25782. };
  25783. /**
  25784. * Creates the VertexData of the Ground.
  25785. */
  25786. VertexData.CreateGround = function (options) {
  25787. var indices = [];
  25788. var positions = [];
  25789. var normals = [];
  25790. var uvs = [];
  25791. var row, col;
  25792. var width = options.width || 1;
  25793. var height = options.height || 1;
  25794. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25795. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25796. for (row = 0; row <= subdivisionsY; row++) {
  25797. for (col = 0; col <= subdivisionsX; col++) {
  25798. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  25799. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25800. positions.push(position.x, position.y, position.z);
  25801. normals.push(normal.x, normal.y, normal.z);
  25802. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  25803. }
  25804. }
  25805. for (row = 0; row < subdivisionsY; row++) {
  25806. for (col = 0; col < subdivisionsX; col++) {
  25807. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25808. indices.push(col + 1 + row * (subdivisionsX + 1));
  25809. indices.push(col + row * (subdivisionsX + 1));
  25810. indices.push(col + (row + 1) * (subdivisionsX + 1));
  25811. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25812. indices.push(col + row * (subdivisionsX + 1));
  25813. }
  25814. }
  25815. // Result
  25816. var vertexData = new VertexData();
  25817. vertexData.indices = indices;
  25818. vertexData.positions = positions;
  25819. vertexData.normals = normals;
  25820. vertexData.uvs = uvs;
  25821. return vertexData;
  25822. };
  25823. /**
  25824. * Creates the VertexData of the TiledGround.
  25825. */
  25826. VertexData.CreateTiledGround = function (options) {
  25827. var xmin = options.xmin || -1.0;
  25828. var zmin = options.zmin || -1.0;
  25829. var xmax = options.xmax || 1.0;
  25830. var zmax = options.zmax || 1.0;
  25831. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25832. var precision = options.precision || { w: 1, h: 1 };
  25833. var indices = [];
  25834. var positions = [];
  25835. var normals = [];
  25836. var uvs = [];
  25837. var row, col, tileRow, tileCol;
  25838. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  25839. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25840. precision.w = (precision.w < 1) ? 1 : precision.w;
  25841. precision.h = (precision.h < 1) ? 1 : precision.h;
  25842. var tileSize = {
  25843. 'w': (xmax - xmin) / subdivisions.w,
  25844. 'h': (zmax - zmin) / subdivisions.h
  25845. };
  25846. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25847. // Indices
  25848. var base = positions.length / 3;
  25849. var rowLength = precision.w + 1;
  25850. for (row = 0; row < precision.h; row++) {
  25851. for (col = 0; col < precision.w; col++) {
  25852. var square = [
  25853. base + col + row * rowLength,
  25854. base + (col + 1) + row * rowLength,
  25855. base + (col + 1) + (row + 1) * rowLength,
  25856. base + col + (row + 1) * rowLength
  25857. ];
  25858. indices.push(square[1]);
  25859. indices.push(square[2]);
  25860. indices.push(square[3]);
  25861. indices.push(square[0]);
  25862. indices.push(square[1]);
  25863. indices.push(square[3]);
  25864. }
  25865. }
  25866. // Position, normals and uvs
  25867. var position = BABYLON.Vector3.Zero();
  25868. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25869. for (row = 0; row <= precision.h; row++) {
  25870. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25871. for (col = 0; col <= precision.w; col++) {
  25872. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25873. position.y = 0;
  25874. positions.push(position.x, position.y, position.z);
  25875. normals.push(normal.x, normal.y, normal.z);
  25876. uvs.push(col / precision.w, row / precision.h);
  25877. }
  25878. }
  25879. }
  25880. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25881. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25882. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25883. }
  25884. }
  25885. // Result
  25886. var vertexData = new VertexData();
  25887. vertexData.indices = indices;
  25888. vertexData.positions = positions;
  25889. vertexData.normals = normals;
  25890. vertexData.uvs = uvs;
  25891. return vertexData;
  25892. };
  25893. /**
  25894. * Creates the VertexData of the Ground designed from a heightmap.
  25895. */
  25896. VertexData.CreateGroundFromHeightMap = function (options) {
  25897. var indices = [];
  25898. var positions = [];
  25899. var normals = [];
  25900. var uvs = [];
  25901. var row, col;
  25902. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25903. // Vertices
  25904. for (row = 0; row <= options.subdivisions; row++) {
  25905. for (col = 0; col <= options.subdivisions; col++) {
  25906. 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));
  25907. // Compute height
  25908. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25909. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25910. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25911. var r = options.buffer[pos] / 255.0;
  25912. var g = options.buffer[pos + 1] / 255.0;
  25913. var b = options.buffer[pos + 2] / 255.0;
  25914. var gradient = r * filter.r + g * filter.g + b * filter.b;
  25915. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25916. // Add vertex
  25917. positions.push(position.x, position.y, position.z);
  25918. normals.push(0, 0, 0);
  25919. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25920. }
  25921. }
  25922. // Indices
  25923. for (row = 0; row < options.subdivisions; row++) {
  25924. for (col = 0; col < options.subdivisions; col++) {
  25925. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25926. indices.push(col + 1 + row * (options.subdivisions + 1));
  25927. indices.push(col + row * (options.subdivisions + 1));
  25928. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25929. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25930. indices.push(col + row * (options.subdivisions + 1));
  25931. }
  25932. }
  25933. // Normals
  25934. VertexData.ComputeNormals(positions, indices, normals);
  25935. // Result
  25936. var vertexData = new VertexData();
  25937. vertexData.indices = indices;
  25938. vertexData.positions = positions;
  25939. vertexData.normals = normals;
  25940. vertexData.uvs = uvs;
  25941. return vertexData;
  25942. };
  25943. /**
  25944. * Creates the VertexData of the Plane.
  25945. */
  25946. VertexData.CreatePlane = function (options) {
  25947. var indices = [];
  25948. var positions = [];
  25949. var normals = [];
  25950. var uvs = [];
  25951. var width = options.width || options.size || 1;
  25952. var height = options.height || options.size || 1;
  25953. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25954. // Vertices
  25955. var halfWidth = width / 2.0;
  25956. var halfHeight = height / 2.0;
  25957. positions.push(-halfWidth, -halfHeight, 0);
  25958. normals.push(0, 0, -1.0);
  25959. uvs.push(0.0, 0.0);
  25960. positions.push(halfWidth, -halfHeight, 0);
  25961. normals.push(0, 0, -1.0);
  25962. uvs.push(1.0, 0.0);
  25963. positions.push(halfWidth, halfHeight, 0);
  25964. normals.push(0, 0, -1.0);
  25965. uvs.push(1.0, 1.0);
  25966. positions.push(-halfWidth, halfHeight, 0);
  25967. normals.push(0, 0, -1.0);
  25968. uvs.push(0.0, 1.0);
  25969. // Indices
  25970. indices.push(0);
  25971. indices.push(1);
  25972. indices.push(2);
  25973. indices.push(0);
  25974. indices.push(2);
  25975. indices.push(3);
  25976. // Sides
  25977. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25978. // Result
  25979. var vertexData = new VertexData();
  25980. vertexData.indices = indices;
  25981. vertexData.positions = positions;
  25982. vertexData.normals = normals;
  25983. vertexData.uvs = uvs;
  25984. return vertexData;
  25985. };
  25986. /**
  25987. * Creates the VertexData of the Disc or regular Polygon.
  25988. */
  25989. VertexData.CreateDisc = function (options) {
  25990. var positions = [];
  25991. var indices = [];
  25992. var normals = [];
  25993. var uvs = [];
  25994. var radius = options.radius || 0.5;
  25995. var tessellation = options.tessellation || 64;
  25996. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25997. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25998. // positions and uvs
  25999. positions.push(0, 0, 0); // disc center first
  26000. uvs.push(0.5, 0.5);
  26001. var theta = Math.PI * 2 * arc;
  26002. var step = theta / tessellation;
  26003. for (var a = 0; a < theta; a += step) {
  26004. var x = Math.cos(a);
  26005. var y = Math.sin(a);
  26006. var u = (x + 1) / 2;
  26007. var v = (1 - y) / 2;
  26008. positions.push(radius * x, radius * y, 0);
  26009. uvs.push(u, v);
  26010. }
  26011. if (arc === 1) {
  26012. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26013. uvs.push(uvs[2], uvs[3]);
  26014. }
  26015. //indices
  26016. var vertexNb = positions.length / 3;
  26017. for (var i = 1; i < vertexNb - 1; i++) {
  26018. indices.push(i + 1, 0, i);
  26019. }
  26020. // result
  26021. VertexData.ComputeNormals(positions, indices, normals);
  26022. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26023. var vertexData = new VertexData();
  26024. vertexData.indices = indices;
  26025. vertexData.positions = positions;
  26026. vertexData.normals = normals;
  26027. vertexData.uvs = uvs;
  26028. return vertexData;
  26029. };
  26030. /**
  26031. * Re-creates the VertexData of the Polygon for sideOrientation.
  26032. */
  26033. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26034. var faceUV = fUV || new Array(3);
  26035. var faceColors = fColors;
  26036. var colors = [];
  26037. // default face colors and UV if undefined
  26038. for (var f = 0; f < 3; f++) {
  26039. if (faceUV[f] === undefined) {
  26040. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26041. }
  26042. if (faceColors && faceColors[f] === undefined) {
  26043. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26044. }
  26045. }
  26046. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26047. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26048. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26049. var indices = polygon.getIndices();
  26050. // set face colours and textures
  26051. var idx = 0;
  26052. var face = 0;
  26053. for (var index = 0; index < normals.length; index += 3) {
  26054. //Edge Face no. 1
  26055. if (Math.abs(normals[index + 1]) == 0) {
  26056. face = 1;
  26057. }
  26058. //Top Face no. 0
  26059. if (normals[index + 1] == 1) {
  26060. face = 0;
  26061. }
  26062. //Bottom Face no. 2
  26063. if (normals[index + 1] == -1) {
  26064. face = 2;
  26065. }
  26066. idx = index / 3;
  26067. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26068. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26069. if (faceColors) {
  26070. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26071. }
  26072. }
  26073. // sides
  26074. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26075. // Result
  26076. var vertexData = new VertexData();
  26077. vertexData.indices = indices;
  26078. vertexData.positions = positions;
  26079. vertexData.normals = normals;
  26080. vertexData.uvs = uvs;
  26081. if (faceColors) {
  26082. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26083. vertexData.colors = totalColors;
  26084. }
  26085. return vertexData;
  26086. };
  26087. /**
  26088. * Creates the VertexData of the IcoSphere.
  26089. */
  26090. VertexData.CreateIcoSphere = function (options) {
  26091. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26092. var radius = options.radius || 1;
  26093. var flat = (options.flat === undefined) ? true : options.flat;
  26094. var subdivisions = options.subdivisions || 4;
  26095. var radiusX = options.radiusX || radius;
  26096. var radiusY = options.radiusY || radius;
  26097. var radiusZ = options.radiusZ || radius;
  26098. var t = (1 + Math.sqrt(5)) / 2;
  26099. // 12 vertex x,y,z
  26100. var ico_vertices = [
  26101. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26102. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26103. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26104. ];
  26105. // index of 3 vertex makes a face of icopshere
  26106. var ico_indices = [
  26107. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26108. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26109. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26110. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26111. ];
  26112. // vertex for uv have aliased position, not for UV
  26113. var vertices_unalias_id = [
  26114. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26115. // vertex alias
  26116. 0,
  26117. 2,
  26118. 3,
  26119. 3,
  26120. 3,
  26121. 4,
  26122. 7,
  26123. 8,
  26124. 9,
  26125. 9,
  26126. 10,
  26127. 11 // 23: B + 12
  26128. ];
  26129. // uv as integer step (not pixels !)
  26130. var ico_vertexuv = [
  26131. 5, 1, 3, 1, 6, 4, 0, 0,
  26132. 5, 3, 4, 2, 2, 2, 4, 0,
  26133. 2, 0, 1, 1, 6, 0, 6, 2,
  26134. // vertex alias (for same vertex on different faces)
  26135. 0, 4,
  26136. 3, 3,
  26137. 4, 4,
  26138. 3, 1,
  26139. 4, 2,
  26140. 4, 4,
  26141. 0, 2,
  26142. 1, 1,
  26143. 2, 2,
  26144. 3, 3,
  26145. 1, 3,
  26146. 2, 4 // 23: B + 12
  26147. ];
  26148. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26149. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26150. // First island of uv mapping
  26151. // v = 4h 3+ 2
  26152. // v = 3h 9+ 4
  26153. // v = 2h 9+ 5 B
  26154. // v = 1h 9 1 0
  26155. // v = 0h 3 8 7 A
  26156. // u = 0 1 2 3 4 5 6 *a
  26157. // Second island of uv mapping
  26158. // v = 4h 0+ B+ 4+
  26159. // v = 3h A+ 2+
  26160. // v = 2h 7+ 6 3+
  26161. // v = 1h 8+ 3+
  26162. // v = 0h
  26163. // u = 0 1 2 3 4 5 6 *a
  26164. // Face layout on texture UV mapping
  26165. // ============
  26166. // \ 4 /\ 16 / ======
  26167. // \ / \ / /\ 11 /
  26168. // \/ 7 \/ / \ /
  26169. // ======= / 10 \/
  26170. // /\ 17 /\ =======
  26171. // / \ / \ \ 15 /\
  26172. // / 8 \/ 12 \ \ / \
  26173. // ============ \/ 6 \
  26174. // \ 18 /\ ============
  26175. // \ / \ \ 5 /\ 0 /
  26176. // \/ 13 \ \ / \ /
  26177. // ======= \/ 1 \/
  26178. // =============
  26179. // /\ 19 /\ 2 /\
  26180. // / \ / \ / \
  26181. // / 14 \/ 9 \/ 3 \
  26182. // ===================
  26183. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26184. var ustep = 138 / 1024;
  26185. var vstep = 239 / 1024;
  26186. var uoffset = 60 / 1024;
  26187. var voffset = 26 / 1024;
  26188. // Second island should have margin, not to touch the first island
  26189. // avoid any borderline artefact in pixel rounding
  26190. var island_u_offset = -40 / 1024;
  26191. var island_v_offset = +20 / 1024;
  26192. // face is either island 0 or 1 :
  26193. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26194. var island = [
  26195. 0, 0, 0, 0, 1,
  26196. 0, 0, 1, 1, 0,
  26197. 0, 0, 1, 1, 0,
  26198. 0, 1, 1, 1, 0 // 15 - 19
  26199. ];
  26200. var indices = [];
  26201. var positions = [];
  26202. var normals = [];
  26203. var uvs = [];
  26204. var current_indice = 0;
  26205. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26206. var face_vertex_pos = new Array(3);
  26207. var face_vertex_uv = new Array(3);
  26208. var v012;
  26209. for (v012 = 0; v012 < 3; v012++) {
  26210. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26211. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26212. }
  26213. // create all with normals
  26214. for (var face = 0; face < 20; face++) {
  26215. // 3 vertex per face
  26216. for (v012 = 0; v012 < 3; v012++) {
  26217. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26218. var v_id = ico_indices[3 * face + v012];
  26219. // vertex have 3D position (x,y,z)
  26220. 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]);
  26221. // Normalize to get normal, then scale to radius
  26222. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26223. // uv Coordinates from vertex ID
  26224. 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);
  26225. }
  26226. // Subdivide the face (interpolate pos, norm, uv)
  26227. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26228. // - norm is linear interpolation of vertex corner normal
  26229. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26230. // - uv is linear interpolation
  26231. //
  26232. // Topology is as below for sub-divide by 2
  26233. // vertex shown as v0,v1,v2
  26234. // interp index is i1 to progress in range [v0,v1[
  26235. // interp index is i2 to progress in range [v0,v2[
  26236. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26237. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26238. //
  26239. //
  26240. // i2 v2
  26241. // ^ ^
  26242. // / / \
  26243. // / / \
  26244. // / / \
  26245. // / / (0,1) \
  26246. // / #---------\
  26247. // / / \ (0,0)'/ \
  26248. // / / \ / \
  26249. // / / \ / \
  26250. // / / (0,0) \ / (1,0) \
  26251. // / #---------#---------\
  26252. // v0 v1
  26253. //
  26254. // --------------------> i1
  26255. //
  26256. // interp of (i1,i2):
  26257. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26258. // along i1 : lerp(x0,x1, i1/(S-i2))
  26259. //
  26260. // centroid of triangle is needed to get help normal computation
  26261. // (c1,c2) are used for centroid location
  26262. var interp_vertex = function (i1, i2, c1, c2) {
  26263. // vertex is interpolated from
  26264. // - face_vertex_pos[0..2]
  26265. // - face_vertex_uv[0..2]
  26266. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26267. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26268. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26269. pos_interp.normalize();
  26270. var vertex_normal;
  26271. if (flat) {
  26272. // in flat mode, recalculate normal as face centroid normal
  26273. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26274. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26275. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26276. }
  26277. else {
  26278. // in smooth mode, recalculate normal from each single vertex position
  26279. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26280. }
  26281. // Vertex normal need correction due to X,Y,Z radius scaling
  26282. vertex_normal.x /= radiusX;
  26283. vertex_normal.y /= radiusY;
  26284. vertex_normal.z /= radiusZ;
  26285. vertex_normal.normalize();
  26286. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26287. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26288. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26289. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26290. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26291. uvs.push(uv_interp.x, uv_interp.y);
  26292. // push each vertex has member of a face
  26293. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26294. indices.push(current_indice);
  26295. current_indice++;
  26296. };
  26297. for (var i2 = 0; i2 < subdivisions; i2++) {
  26298. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26299. // face : (i1,i2) for /\ :
  26300. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26301. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26302. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26303. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26304. if (i1 + i2 + 1 < subdivisions) {
  26305. // face : (i1,i2)' for \/ :
  26306. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26307. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26308. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26309. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26310. }
  26311. }
  26312. }
  26313. }
  26314. // Sides
  26315. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26316. // Result
  26317. var vertexData = new VertexData();
  26318. vertexData.indices = indices;
  26319. vertexData.positions = positions;
  26320. vertexData.normals = normals;
  26321. vertexData.uvs = uvs;
  26322. return vertexData;
  26323. };
  26324. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26325. /**
  26326. * Creates the VertexData of the Polyhedron.
  26327. */
  26328. VertexData.CreatePolyhedron = function (options) {
  26329. // provided polyhedron types :
  26330. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26331. // 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)
  26332. var polyhedra = [];
  26333. 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]] };
  26334. 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]] };
  26335. polyhedra[2] = {
  26336. 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]],
  26337. 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]]
  26338. };
  26339. polyhedra[3] = {
  26340. 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]],
  26341. 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]]
  26342. };
  26343. polyhedra[4] = {
  26344. 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]],
  26345. 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]]
  26346. };
  26347. 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]] };
  26348. 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]] };
  26349. 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]] };
  26350. 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]] };
  26351. 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]] };
  26352. 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]] };
  26353. 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]] };
  26354. 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]] };
  26355. 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]] };
  26356. polyhedra[14] = {
  26357. 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]],
  26358. 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]]
  26359. };
  26360. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26361. var size = options.size;
  26362. var sizeX = options.sizeX || size || 1;
  26363. var sizeY = options.sizeY || size || 1;
  26364. var sizeZ = options.sizeZ || size || 1;
  26365. var data = options.custom || polyhedra[type];
  26366. var nbfaces = data.face.length;
  26367. var faceUV = options.faceUV || new Array(nbfaces);
  26368. var faceColors = options.faceColors;
  26369. var flat = (options.flat === undefined) ? true : options.flat;
  26370. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26371. var positions = [];
  26372. var indices = [];
  26373. var normals = [];
  26374. var uvs = [];
  26375. var colors = [];
  26376. var index = 0;
  26377. var faceIdx = 0; // face cursor in the array "indexes"
  26378. var indexes = [];
  26379. var i = 0;
  26380. var f = 0;
  26381. var u, v, ang, x, y, tmp;
  26382. // default face colors and UV if undefined
  26383. if (flat) {
  26384. for (f = 0; f < nbfaces; f++) {
  26385. if (faceColors && faceColors[f] === undefined) {
  26386. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26387. }
  26388. if (faceUV && faceUV[f] === undefined) {
  26389. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26390. }
  26391. }
  26392. }
  26393. if (!flat) {
  26394. for (i = 0; i < data.vertex.length; i++) {
  26395. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26396. uvs.push(0, 0);
  26397. }
  26398. for (f = 0; f < nbfaces; f++) {
  26399. for (i = 0; i < data.face[f].length - 2; i++) {
  26400. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26401. }
  26402. }
  26403. }
  26404. else {
  26405. for (f = 0; f < nbfaces; f++) {
  26406. var fl = data.face[f].length; // number of vertices of the current face
  26407. ang = 2 * Math.PI / fl;
  26408. x = 0.5 * Math.tan(ang / 2);
  26409. y = 0.5;
  26410. // positions, uvs, colors
  26411. for (i = 0; i < fl; i++) {
  26412. // positions
  26413. 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);
  26414. indexes.push(index);
  26415. index++;
  26416. // uvs
  26417. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26418. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26419. uvs.push(u, v);
  26420. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26421. y = x * Math.sin(ang) + y * Math.cos(ang);
  26422. x = tmp;
  26423. // colors
  26424. if (faceColors) {
  26425. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26426. }
  26427. }
  26428. // indices from indexes
  26429. for (i = 0; i < fl - 2; i++) {
  26430. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26431. }
  26432. faceIdx += fl;
  26433. }
  26434. }
  26435. VertexData.ComputeNormals(positions, indices, normals);
  26436. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26437. var vertexData = new VertexData();
  26438. vertexData.positions = positions;
  26439. vertexData.indices = indices;
  26440. vertexData.normals = normals;
  26441. vertexData.uvs = uvs;
  26442. if (faceColors && flat) {
  26443. vertexData.colors = colors;
  26444. }
  26445. return vertexData;
  26446. };
  26447. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26448. /**
  26449. * Creates the VertexData of the Torus Knot.
  26450. */
  26451. VertexData.CreateTorusKnot = function (options) {
  26452. var indices = [];
  26453. var positions = [];
  26454. var normals = [];
  26455. var uvs = [];
  26456. var radius = options.radius || 2;
  26457. var tube = options.tube || 0.5;
  26458. var radialSegments = options.radialSegments || 32;
  26459. var tubularSegments = options.tubularSegments || 32;
  26460. var p = options.p || 2;
  26461. var q = options.q || 3;
  26462. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26463. // Helper
  26464. var getPos = function (angle) {
  26465. var cu = Math.cos(angle);
  26466. var su = Math.sin(angle);
  26467. var quOverP = q / p * angle;
  26468. var cs = Math.cos(quOverP);
  26469. var tx = radius * (2 + cs) * 0.5 * cu;
  26470. var ty = radius * (2 + cs) * su * 0.5;
  26471. var tz = radius * Math.sin(quOverP) * 0.5;
  26472. return new BABYLON.Vector3(tx, ty, tz);
  26473. };
  26474. // Vertices
  26475. var i;
  26476. var j;
  26477. for (i = 0; i <= radialSegments; i++) {
  26478. var modI = i % radialSegments;
  26479. var u = modI / radialSegments * 2 * p * Math.PI;
  26480. var p1 = getPos(u);
  26481. var p2 = getPos(u + 0.01);
  26482. var tang = p2.subtract(p1);
  26483. var n = p2.add(p1);
  26484. var bitan = BABYLON.Vector3.Cross(tang, n);
  26485. n = BABYLON.Vector3.Cross(bitan, tang);
  26486. bitan.normalize();
  26487. n.normalize();
  26488. for (j = 0; j < tubularSegments; j++) {
  26489. var modJ = j % tubularSegments;
  26490. var v = modJ / tubularSegments * 2 * Math.PI;
  26491. var cx = -tube * Math.cos(v);
  26492. var cy = tube * Math.sin(v);
  26493. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26494. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26495. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26496. uvs.push(i / radialSegments);
  26497. uvs.push(j / tubularSegments);
  26498. }
  26499. }
  26500. for (i = 0; i < radialSegments; i++) {
  26501. for (j = 0; j < tubularSegments; j++) {
  26502. var jNext = (j + 1) % tubularSegments;
  26503. var a = i * tubularSegments + j;
  26504. var b = (i + 1) * tubularSegments + j;
  26505. var c = (i + 1) * tubularSegments + jNext;
  26506. var d = i * tubularSegments + jNext;
  26507. indices.push(d);
  26508. indices.push(b);
  26509. indices.push(a);
  26510. indices.push(d);
  26511. indices.push(c);
  26512. indices.push(b);
  26513. }
  26514. }
  26515. // Normals
  26516. VertexData.ComputeNormals(positions, indices, normals);
  26517. // Sides
  26518. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26519. // Result
  26520. var vertexData = new VertexData();
  26521. vertexData.indices = indices;
  26522. vertexData.positions = positions;
  26523. vertexData.normals = normals;
  26524. vertexData.uvs = uvs;
  26525. return vertexData;
  26526. };
  26527. // Tools
  26528. /**
  26529. * @param {any} - positions (number[] or Float32Array)
  26530. * @param {any} - indices (number[] or Uint16Array)
  26531. * @param {any} - normals (number[] or Float32Array)
  26532. * options (optional) :
  26533. * facetPositions : optional array of facet positions (vector3)
  26534. * facetNormals : optional array of facet normals (vector3)
  26535. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26536. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26537. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26538. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26539. * bInfo : optional bounding info, required for facetPartitioning computation
  26540. */
  26541. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26542. // temporary scalar variables
  26543. var index = 0; // facet index
  26544. var p1p2x = 0.0; // p1p2 vector x coordinate
  26545. var p1p2y = 0.0; // p1p2 vector y coordinate
  26546. var p1p2z = 0.0; // p1p2 vector z coordinate
  26547. var p3p2x = 0.0; // p3p2 vector x coordinate
  26548. var p3p2y = 0.0; // p3p2 vector y coordinate
  26549. var p3p2z = 0.0; // p3p2 vector z coordinate
  26550. var faceNormalx = 0.0; // facet normal x coordinate
  26551. var faceNormaly = 0.0; // facet normal y coordinate
  26552. var faceNormalz = 0.0; // facet normal z coordinate
  26553. var length = 0.0; // facet normal length before normalization
  26554. var v1x = 0; // vector1 x index in the positions array
  26555. var v1y = 0; // vector1 y index in the positions array
  26556. var v1z = 0; // vector1 z index in the positions array
  26557. var v2x = 0; // vector2 x index in the positions array
  26558. var v2y = 0; // vector2 y index in the positions array
  26559. var v2z = 0; // vector2 z index in the positions array
  26560. var v3x = 0; // vector3 x index in the positions array
  26561. var v3y = 0; // vector3 y index in the positions array
  26562. var v3z = 0; // vector3 z index in the positions array
  26563. var computeFacetNormals = false;
  26564. var computeFacetPositions = false;
  26565. var computeFacetPartitioning = false;
  26566. var faceNormalSign = 1;
  26567. if (options) {
  26568. computeFacetNormals = (options.facetNormals) ? true : false;
  26569. computeFacetPositions = (options.facetPositions) ? true : false;
  26570. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26571. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26572. }
  26573. // facetPartitioning reinit if needed
  26574. if (computeFacetPartitioning) {
  26575. var ox = 0; // X partitioning index for facet position
  26576. var oy = 0; // Y partinioning index for facet position
  26577. var oz = 0; // Z partinioning index for facet position
  26578. var b1x = 0; // X partitioning index for facet v1 vertex
  26579. var b1y = 0; // Y partitioning index for facet v1 vertex
  26580. var b1z = 0; // z partitioning index for facet v1 vertex
  26581. var b2x = 0; // X partitioning index for facet v2 vertex
  26582. var b2y = 0; // Y partitioning index for facet v2 vertex
  26583. var b2z = 0; // Z partitioning index for facet v2 vertex
  26584. var b3x = 0; // X partitioning index for facet v3 vertex
  26585. var b3y = 0; // Y partitioning index for facet v3 vertex
  26586. var b3z = 0; // Z partitioning index for facet v3 vertex
  26587. var block_idx_o = 0; // facet barycenter block index
  26588. var block_idx_v1 = 0; // v1 vertex block index
  26589. var block_idx_v2 = 0; // v2 vertex block index
  26590. var block_idx_v3 = 0; // v3 vertex block index
  26591. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26592. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26593. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26594. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26595. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26596. var subSq = options.subDiv.max * options.subDiv.max;
  26597. options.facetPartitioning.length = 0;
  26598. }
  26599. // reset the normals
  26600. for (index = 0; index < positions.length; index++) {
  26601. normals[index] = 0.0;
  26602. }
  26603. // Loop : 1 indice triplet = 1 facet
  26604. var nbFaces = indices.length / 3;
  26605. for (index = 0; index < nbFaces; index++) {
  26606. // get the indexes of the coordinates of each vertex of the facet
  26607. v1x = indices[index * 3] * 3;
  26608. v1y = v1x + 1;
  26609. v1z = v1x + 2;
  26610. v2x = indices[index * 3 + 1] * 3;
  26611. v2y = v2x + 1;
  26612. v2z = v2x + 2;
  26613. v3x = indices[index * 3 + 2] * 3;
  26614. v3y = v3x + 1;
  26615. v3z = v3x + 2;
  26616. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26617. p1p2y = positions[v1y] - positions[v2y];
  26618. p1p2z = positions[v1z] - positions[v2z];
  26619. p3p2x = positions[v3x] - positions[v2x];
  26620. p3p2y = positions[v3y] - positions[v2y];
  26621. p3p2z = positions[v3z] - positions[v2z];
  26622. // compute the face normal with the cross product
  26623. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26624. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26625. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26626. // normalize this normal and store it in the array facetData
  26627. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26628. length = (length === 0) ? 1.0 : length;
  26629. faceNormalx /= length;
  26630. faceNormaly /= length;
  26631. faceNormalz /= length;
  26632. if (computeFacetNormals) {
  26633. options.facetNormals[index].x = faceNormalx;
  26634. options.facetNormals[index].y = faceNormaly;
  26635. options.facetNormals[index].z = faceNormalz;
  26636. }
  26637. if (computeFacetPositions) {
  26638. // compute and the facet barycenter coordinates in the array facetPositions
  26639. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26640. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26641. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26642. }
  26643. if (computeFacetPartitioning) {
  26644. // store the facet indexes in arrays in the main facetPartitioning array :
  26645. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26646. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26647. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26648. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26649. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26650. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26651. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26652. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26653. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26654. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26655. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26656. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26657. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26658. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26659. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26660. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26661. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26662. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26663. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26664. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26665. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26666. // push each facet index in each block containing the vertex
  26667. options.facetPartitioning[block_idx_v1].push(index);
  26668. if (block_idx_v2 != block_idx_v1) {
  26669. options.facetPartitioning[block_idx_v2].push(index);
  26670. }
  26671. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26672. options.facetPartitioning[block_idx_v3].push(index);
  26673. }
  26674. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26675. options.facetPartitioning[block_idx_o].push(index);
  26676. }
  26677. }
  26678. // compute the normals anyway
  26679. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26680. normals[v1y] += faceNormaly;
  26681. normals[v1z] += faceNormalz;
  26682. normals[v2x] += faceNormalx;
  26683. normals[v2y] += faceNormaly;
  26684. normals[v2z] += faceNormalz;
  26685. normals[v3x] += faceNormalx;
  26686. normals[v3y] += faceNormaly;
  26687. normals[v3z] += faceNormalz;
  26688. }
  26689. // last normalization of each normal
  26690. for (index = 0; index < normals.length / 3; index++) {
  26691. faceNormalx = normals[index * 3];
  26692. faceNormaly = normals[index * 3 + 1];
  26693. faceNormalz = normals[index * 3 + 2];
  26694. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26695. length = (length === 0) ? 1.0 : length;
  26696. faceNormalx /= length;
  26697. faceNormaly /= length;
  26698. faceNormalz /= length;
  26699. normals[index * 3] = faceNormalx;
  26700. normals[index * 3 + 1] = faceNormaly;
  26701. normals[index * 3 + 2] = faceNormalz;
  26702. }
  26703. };
  26704. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26705. var li = indices.length;
  26706. var ln = normals.length;
  26707. var i;
  26708. var n;
  26709. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26710. switch (sideOrientation) {
  26711. case BABYLON.Mesh.FRONTSIDE:
  26712. // nothing changed
  26713. break;
  26714. case BABYLON.Mesh.BACKSIDE:
  26715. var tmp;
  26716. // indices
  26717. for (i = 0; i < li; i += 3) {
  26718. tmp = indices[i];
  26719. indices[i] = indices[i + 2];
  26720. indices[i + 2] = tmp;
  26721. }
  26722. // normals
  26723. for (n = 0; n < ln; n++) {
  26724. normals[n] = -normals[n];
  26725. }
  26726. break;
  26727. case BABYLON.Mesh.DOUBLESIDE:
  26728. // positions
  26729. var lp = positions.length;
  26730. var l = lp / 3;
  26731. for (var p = 0; p < lp; p++) {
  26732. positions[lp + p] = positions[p];
  26733. }
  26734. // indices
  26735. for (i = 0; i < li; i += 3) {
  26736. indices[i + li] = indices[i + 2] + l;
  26737. indices[i + 1 + li] = indices[i + 1] + l;
  26738. indices[i + 2 + li] = indices[i] + l;
  26739. }
  26740. // normals
  26741. for (n = 0; n < ln; n++) {
  26742. normals[ln + n] = -normals[n];
  26743. }
  26744. // uvs
  26745. var lu = uvs.length;
  26746. var u = 0;
  26747. for (u = 0; u < lu; u++) {
  26748. uvs[u + lu] = uvs[u];
  26749. }
  26750. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26751. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26752. u = 0;
  26753. for (i = 0; i < lu / 2; i++) {
  26754. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  26755. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  26756. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  26757. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  26758. u += 2;
  26759. }
  26760. break;
  26761. }
  26762. };
  26763. /**
  26764. * Creates a new VertexData from the imported parameters.
  26765. */
  26766. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26767. var vertexData = new VertexData();
  26768. // positions
  26769. var positions = parsedVertexData.positions;
  26770. if (positions) {
  26771. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26772. }
  26773. // normals
  26774. var normals = parsedVertexData.normals;
  26775. if (normals) {
  26776. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26777. }
  26778. // tangents
  26779. var tangents = parsedVertexData.tangents;
  26780. if (tangents) {
  26781. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  26782. }
  26783. // uvs
  26784. var uvs = parsedVertexData.uvs;
  26785. if (uvs) {
  26786. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26787. }
  26788. // uv2s
  26789. var uv2s = parsedVertexData.uv2s;
  26790. if (uv2s) {
  26791. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26792. }
  26793. // uv3s
  26794. var uv3s = parsedVertexData.uv3s;
  26795. if (uv3s) {
  26796. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26797. }
  26798. // uv4s
  26799. var uv4s = parsedVertexData.uv4s;
  26800. if (uv4s) {
  26801. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26802. }
  26803. // uv5s
  26804. var uv5s = parsedVertexData.uv5s;
  26805. if (uv5s) {
  26806. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26807. }
  26808. // uv6s
  26809. var uv6s = parsedVertexData.uv6s;
  26810. if (uv6s) {
  26811. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26812. }
  26813. // colors
  26814. var colors = parsedVertexData.colors;
  26815. if (colors) {
  26816. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26817. }
  26818. // matricesIndices
  26819. var matricesIndices = parsedVertexData.matricesIndices;
  26820. if (matricesIndices) {
  26821. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26822. }
  26823. // matricesWeights
  26824. var matricesWeights = parsedVertexData.matricesWeights;
  26825. if (matricesWeights) {
  26826. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26827. }
  26828. // indices
  26829. var indices = parsedVertexData.indices;
  26830. if (indices) {
  26831. vertexData.indices = indices;
  26832. }
  26833. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26834. };
  26835. return VertexData;
  26836. }());
  26837. BABYLON.VertexData = VertexData;
  26838. })(BABYLON || (BABYLON = {}));
  26839. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  26840. var BABYLON;
  26841. (function (BABYLON) {
  26842. var Geometry = (function () {
  26843. function Geometry(id, scene, vertexData, updatable, mesh) {
  26844. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26845. this._totalVertices = 0;
  26846. this._isDisposed = false;
  26847. this.id = id;
  26848. this._engine = scene.getEngine();
  26849. this._meshes = [];
  26850. this._scene = scene;
  26851. //Init vertex buffer cache
  26852. this._vertexBuffers = {};
  26853. this._indices = [];
  26854. // vertexData
  26855. if (vertexData) {
  26856. this.setAllVerticesData(vertexData, updatable);
  26857. }
  26858. else {
  26859. this._totalVertices = 0;
  26860. this._indices = [];
  26861. }
  26862. if (this._engine.getCaps().vertexArrayObject) {
  26863. this._vertexArrayObjects = {};
  26864. }
  26865. // applyToMesh
  26866. if (mesh) {
  26867. if (mesh.getClassName() === "LinesMesh") {
  26868. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  26869. this.updateExtend();
  26870. }
  26871. this.applyToMesh(mesh);
  26872. mesh.computeWorldMatrix(true);
  26873. }
  26874. }
  26875. Object.defineProperty(Geometry.prototype, "boundingBias", {
  26876. /**
  26877. * 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
  26878. * @returns The Bias Vector
  26879. */
  26880. get: function () {
  26881. return this._boundingBias;
  26882. },
  26883. set: function (value) {
  26884. if (this._boundingBias && this._boundingBias.equals(value)) {
  26885. return;
  26886. }
  26887. this._boundingBias = value.clone();
  26888. this.updateBoundingInfo(true, null);
  26889. },
  26890. enumerable: true,
  26891. configurable: true
  26892. });
  26893. Object.defineProperty(Geometry.prototype, "extend", {
  26894. get: function () {
  26895. return this._extend;
  26896. },
  26897. enumerable: true,
  26898. configurable: true
  26899. });
  26900. Geometry.prototype.getScene = function () {
  26901. return this._scene;
  26902. };
  26903. Geometry.prototype.getEngine = function () {
  26904. return this._engine;
  26905. };
  26906. Geometry.prototype.isReady = function () {
  26907. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26908. };
  26909. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  26910. get: function () {
  26911. for (var index = 0; index < this._meshes.length; index++) {
  26912. if (!this._meshes[index].doNotSerialize) {
  26913. return false;
  26914. }
  26915. }
  26916. return true;
  26917. },
  26918. enumerable: true,
  26919. configurable: true
  26920. });
  26921. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26922. vertexData.applyToGeometry(this, updatable);
  26923. this.notifyUpdate();
  26924. };
  26925. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26926. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26927. this.setVerticesBuffer(buffer);
  26928. };
  26929. Geometry.prototype.removeVerticesData = function (kind) {
  26930. if (this._vertexBuffers[kind]) {
  26931. this._vertexBuffers[kind].dispose();
  26932. delete this._vertexBuffers[kind];
  26933. }
  26934. };
  26935. Geometry.prototype.setVerticesBuffer = function (buffer) {
  26936. var kind = buffer.getKind();
  26937. if (this._vertexBuffers[kind]) {
  26938. this._vertexBuffers[kind].dispose();
  26939. }
  26940. this._vertexBuffers[kind] = buffer;
  26941. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26942. var data = buffer.getData();
  26943. var stride = buffer.getStrideSize();
  26944. this._totalVertices = data.length / stride;
  26945. this.updateExtend(data, stride);
  26946. this._resetPointsArrayCache();
  26947. var meshes = this._meshes;
  26948. var numOfMeshes = meshes.length;
  26949. for (var index = 0; index < numOfMeshes; index++) {
  26950. var mesh = meshes[index];
  26951. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26952. mesh._createGlobalSubMesh();
  26953. mesh.computeWorldMatrix(true);
  26954. }
  26955. }
  26956. this.notifyUpdate(kind);
  26957. if (this._vertexArrayObjects) {
  26958. this._disposeVertexArrayObjects();
  26959. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  26960. }
  26961. };
  26962. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26963. var vertexBuffer = this.getVertexBuffer(kind);
  26964. if (!vertexBuffer) {
  26965. return;
  26966. }
  26967. vertexBuffer.updateDirectly(data, offset);
  26968. this.notifyUpdate(kind);
  26969. };
  26970. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26971. var vertexBuffer = this.getVertexBuffer(kind);
  26972. if (!vertexBuffer) {
  26973. return;
  26974. }
  26975. vertexBuffer.update(data);
  26976. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26977. var stride = vertexBuffer.getStrideSize();
  26978. this._totalVertices = data.length / stride;
  26979. this.updateBoundingInfo(updateExtends, data);
  26980. }
  26981. this.notifyUpdate(kind);
  26982. };
  26983. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  26984. if (updateExtends) {
  26985. this.updateExtend(data);
  26986. }
  26987. var meshes = this._meshes;
  26988. var numOfMeshes = meshes.length;
  26989. this._resetPointsArrayCache();
  26990. for (var index = 0; index < numOfMeshes; index++) {
  26991. var mesh = meshes[index];
  26992. if (updateExtends) {
  26993. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26994. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26995. var subMesh = mesh.subMeshes[subIndex];
  26996. subMesh.refreshBoundingInfo();
  26997. }
  26998. }
  26999. }
  27000. };
  27001. Geometry.prototype._bind = function (effect, indexToBind) {
  27002. if (indexToBind === void 0) { indexToBind = undefined; }
  27003. if (indexToBind === undefined) {
  27004. indexToBind = this._indexBuffer;
  27005. }
  27006. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27007. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27008. return;
  27009. }
  27010. // Using VAO
  27011. if (!this._vertexArrayObjects[effect.key]) {
  27012. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27013. }
  27014. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27015. };
  27016. Geometry.prototype.getTotalVertices = function () {
  27017. if (!this.isReady()) {
  27018. return 0;
  27019. }
  27020. return this._totalVertices;
  27021. };
  27022. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27023. var vertexBuffer = this.getVertexBuffer(kind);
  27024. if (!vertexBuffer) {
  27025. return null;
  27026. }
  27027. var orig = vertexBuffer.getData();
  27028. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27029. return orig;
  27030. }
  27031. else {
  27032. var len = orig.length;
  27033. var copy = [];
  27034. for (var i = 0; i < len; i++) {
  27035. copy.push(orig[i]);
  27036. }
  27037. return copy;
  27038. }
  27039. };
  27040. Geometry.prototype.getVertexBuffer = function (kind) {
  27041. if (!this.isReady()) {
  27042. return null;
  27043. }
  27044. return this._vertexBuffers[kind];
  27045. };
  27046. Geometry.prototype.getVertexBuffers = function () {
  27047. if (!this.isReady()) {
  27048. return null;
  27049. }
  27050. return this._vertexBuffers;
  27051. };
  27052. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27053. if (!this._vertexBuffers) {
  27054. if (this._delayInfo) {
  27055. return this._delayInfo.indexOf(kind) !== -1;
  27056. }
  27057. return false;
  27058. }
  27059. return this._vertexBuffers[kind] !== undefined;
  27060. };
  27061. Geometry.prototype.getVerticesDataKinds = function () {
  27062. var result = [];
  27063. var kind;
  27064. if (!this._vertexBuffers && this._delayInfo) {
  27065. for (kind in this._delayInfo) {
  27066. result.push(kind);
  27067. }
  27068. }
  27069. else {
  27070. for (kind in this._vertexBuffers) {
  27071. result.push(kind);
  27072. }
  27073. }
  27074. return result;
  27075. };
  27076. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27077. if (this._indexBuffer) {
  27078. this._engine._releaseBuffer(this._indexBuffer);
  27079. }
  27080. this._disposeVertexArrayObjects();
  27081. this._indices = indices;
  27082. if (this._meshes.length !== 0 && this._indices) {
  27083. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27084. }
  27085. if (totalVertices !== undefined) {
  27086. this._totalVertices = totalVertices;
  27087. }
  27088. var meshes = this._meshes;
  27089. var numOfMeshes = meshes.length;
  27090. for (var index = 0; index < numOfMeshes; index++) {
  27091. meshes[index]._createGlobalSubMesh();
  27092. }
  27093. this.notifyUpdate();
  27094. };
  27095. Geometry.prototype.getTotalIndices = function () {
  27096. if (!this.isReady()) {
  27097. return 0;
  27098. }
  27099. return this._indices.length;
  27100. };
  27101. Geometry.prototype.getIndices = function (copyWhenShared) {
  27102. if (!this.isReady()) {
  27103. return null;
  27104. }
  27105. var orig = this._indices;
  27106. if (!copyWhenShared || this._meshes.length === 1) {
  27107. return orig;
  27108. }
  27109. else {
  27110. var len = orig.length;
  27111. var copy = [];
  27112. for (var i = 0; i < len; i++) {
  27113. copy.push(orig[i]);
  27114. }
  27115. return copy;
  27116. }
  27117. };
  27118. Geometry.prototype.getIndexBuffer = function () {
  27119. if (!this.isReady()) {
  27120. return null;
  27121. }
  27122. return this._indexBuffer;
  27123. };
  27124. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27125. if (!effect || !this._vertexArrayObjects) {
  27126. return;
  27127. }
  27128. if (this._vertexArrayObjects[effect.key]) {
  27129. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27130. delete this._vertexArrayObjects[effect.key];
  27131. }
  27132. };
  27133. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27134. var meshes = this._meshes;
  27135. var index = meshes.indexOf(mesh);
  27136. if (index === -1) {
  27137. return;
  27138. }
  27139. meshes.splice(index, 1);
  27140. mesh._geometry = null;
  27141. if (meshes.length === 0 && shouldDispose) {
  27142. this.dispose();
  27143. }
  27144. };
  27145. Geometry.prototype.applyToMesh = function (mesh) {
  27146. if (mesh._geometry === this) {
  27147. return;
  27148. }
  27149. var previousGeometry = mesh._geometry;
  27150. if (previousGeometry) {
  27151. previousGeometry.releaseForMesh(mesh);
  27152. }
  27153. var meshes = this._meshes;
  27154. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27155. mesh._geometry = this;
  27156. this._scene.pushGeometry(this);
  27157. meshes.push(mesh);
  27158. if (this.isReady()) {
  27159. this._applyToMesh(mesh);
  27160. }
  27161. else {
  27162. mesh._boundingInfo = this._boundingInfo;
  27163. }
  27164. };
  27165. Geometry.prototype.updateExtend = function (data, stride) {
  27166. if (data === void 0) { data = null; }
  27167. if (!data) {
  27168. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27169. }
  27170. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27171. };
  27172. Geometry.prototype._applyToMesh = function (mesh) {
  27173. var numOfMeshes = this._meshes.length;
  27174. // vertexBuffers
  27175. for (var kind in this._vertexBuffers) {
  27176. if (numOfMeshes === 1) {
  27177. this._vertexBuffers[kind].create();
  27178. }
  27179. var buffer = this._vertexBuffers[kind].getBuffer();
  27180. if (buffer)
  27181. buffer.references = numOfMeshes;
  27182. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27183. if (!this._extend) {
  27184. this.updateExtend(this._vertexBuffers[kind].getData());
  27185. }
  27186. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27187. mesh._createGlobalSubMesh();
  27188. //bounding info was just created again, world matrix should be applied again.
  27189. mesh._updateBoundingInfo();
  27190. }
  27191. }
  27192. // indexBuffer
  27193. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27194. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27195. }
  27196. if (this._indexBuffer) {
  27197. this._indexBuffer.references = numOfMeshes;
  27198. }
  27199. };
  27200. Geometry.prototype.notifyUpdate = function (kind) {
  27201. if (this.onGeometryUpdated) {
  27202. this.onGeometryUpdated(this, kind);
  27203. }
  27204. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27205. var mesh = _a[_i];
  27206. mesh._markSubMeshesAsAttributesDirty();
  27207. }
  27208. };
  27209. Geometry.prototype.load = function (scene, onLoaded) {
  27210. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27211. return;
  27212. }
  27213. if (this.isReady()) {
  27214. if (onLoaded) {
  27215. onLoaded();
  27216. }
  27217. return;
  27218. }
  27219. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27220. this._queueLoad(scene, onLoaded);
  27221. };
  27222. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27223. var _this = this;
  27224. scene._addPendingData(this);
  27225. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27226. _this._delayLoadingFunction(JSON.parse(data), _this);
  27227. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27228. _this._delayInfo = [];
  27229. scene._removePendingData(_this);
  27230. var meshes = _this._meshes;
  27231. var numOfMeshes = meshes.length;
  27232. for (var index = 0; index < numOfMeshes; index++) {
  27233. _this._applyToMesh(meshes[index]);
  27234. }
  27235. if (onLoaded) {
  27236. onLoaded();
  27237. }
  27238. }, function () { }, scene.database);
  27239. };
  27240. /**
  27241. * Invert the geometry to move from a right handed system to a left handed one.
  27242. */
  27243. Geometry.prototype.toLeftHanded = function () {
  27244. // Flip faces
  27245. var tIndices = this.getIndices(false);
  27246. if (tIndices != null && tIndices.length > 0) {
  27247. for (var i = 0; i < tIndices.length; i += 3) {
  27248. var tTemp = tIndices[i + 0];
  27249. tIndices[i + 0] = tIndices[i + 2];
  27250. tIndices[i + 2] = tTemp;
  27251. }
  27252. this.setIndices(tIndices);
  27253. }
  27254. // Negate position.z
  27255. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27256. if (tPositions != null && tPositions.length > 0) {
  27257. for (var i = 0; i < tPositions.length; i += 3) {
  27258. tPositions[i + 2] = -tPositions[i + 2];
  27259. }
  27260. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27261. }
  27262. // Negate normal.z
  27263. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27264. if (tNormals != null && tNormals.length > 0) {
  27265. for (var i = 0; i < tNormals.length; i += 3) {
  27266. tNormals[i + 2] = -tNormals[i + 2];
  27267. }
  27268. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27269. }
  27270. };
  27271. // Cache
  27272. Geometry.prototype._resetPointsArrayCache = function () {
  27273. this._positions = null;
  27274. };
  27275. Geometry.prototype._generatePointsArray = function () {
  27276. if (this._positions)
  27277. return true;
  27278. this._positions = [];
  27279. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27280. if (!data) {
  27281. return false;
  27282. }
  27283. for (var index = 0; index < data.length; index += 3) {
  27284. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27285. }
  27286. return true;
  27287. };
  27288. Geometry.prototype.isDisposed = function () {
  27289. return this._isDisposed;
  27290. };
  27291. Geometry.prototype._disposeVertexArrayObjects = function () {
  27292. if (this._vertexArrayObjects) {
  27293. for (var kind in this._vertexArrayObjects) {
  27294. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27295. }
  27296. this._vertexArrayObjects = {};
  27297. }
  27298. };
  27299. Geometry.prototype.dispose = function () {
  27300. var meshes = this._meshes;
  27301. var numOfMeshes = meshes.length;
  27302. var index;
  27303. for (index = 0; index < numOfMeshes; index++) {
  27304. this.releaseForMesh(meshes[index]);
  27305. }
  27306. this._meshes = [];
  27307. this._disposeVertexArrayObjects();
  27308. for (var kind in this._vertexBuffers) {
  27309. this._vertexBuffers[kind].dispose();
  27310. }
  27311. this._vertexBuffers = {};
  27312. this._totalVertices = 0;
  27313. if (this._indexBuffer) {
  27314. this._engine._releaseBuffer(this._indexBuffer);
  27315. }
  27316. this._indexBuffer = null;
  27317. this._indices = [];
  27318. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27319. this.delayLoadingFile = null;
  27320. this._delayLoadingFunction = null;
  27321. this._delayInfo = [];
  27322. this._boundingInfo = null;
  27323. this._scene.removeGeometry(this);
  27324. this._isDisposed = true;
  27325. };
  27326. Geometry.prototype.copy = function (id) {
  27327. var vertexData = new BABYLON.VertexData();
  27328. vertexData.indices = [];
  27329. var indices = this.getIndices();
  27330. for (var index = 0; index < indices.length; index++) {
  27331. vertexData.indices.push(indices[index]);
  27332. }
  27333. var updatable = false;
  27334. var stopChecking = false;
  27335. var kind;
  27336. for (kind in this._vertexBuffers) {
  27337. // using slice() to make a copy of the array and not just reference it
  27338. var data = this.getVerticesData(kind);
  27339. if (data instanceof Float32Array) {
  27340. vertexData.set(new Float32Array(data), kind);
  27341. }
  27342. else {
  27343. vertexData.set(data.slice(0), kind);
  27344. }
  27345. if (!stopChecking) {
  27346. updatable = this.getVertexBuffer(kind).isUpdatable();
  27347. stopChecking = !updatable;
  27348. }
  27349. }
  27350. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27351. geometry.delayLoadState = this.delayLoadState;
  27352. geometry.delayLoadingFile = this.delayLoadingFile;
  27353. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27354. for (kind in this._delayInfo) {
  27355. geometry._delayInfo = geometry._delayInfo || [];
  27356. geometry._delayInfo.push(kind);
  27357. }
  27358. // Bounding info
  27359. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27360. return geometry;
  27361. };
  27362. Geometry.prototype.serialize = function () {
  27363. var serializationObject = {};
  27364. serializationObject.id = this.id;
  27365. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27366. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27367. }
  27368. return serializationObject;
  27369. };
  27370. Geometry.prototype.toNumberArray = function (origin) {
  27371. if (Array.isArray(origin)) {
  27372. return origin;
  27373. }
  27374. else {
  27375. return Array.prototype.slice.call(origin);
  27376. }
  27377. };
  27378. Geometry.prototype.serializeVerticeData = function () {
  27379. var serializationObject = this.serialize();
  27380. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27381. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27382. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27383. serializationObject.positions._updatable = true;
  27384. }
  27385. }
  27386. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27387. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27388. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27389. serializationObject.normals._updatable = true;
  27390. }
  27391. }
  27392. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27393. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27394. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27395. serializationObject.uvs._updatable = true;
  27396. }
  27397. }
  27398. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27399. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27400. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27401. serializationObject.uv2s._updatable = true;
  27402. }
  27403. }
  27404. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27405. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27406. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27407. serializationObject.uv3s._updatable = true;
  27408. }
  27409. }
  27410. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27411. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27412. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27413. serializationObject.uv4s._updatable = true;
  27414. }
  27415. }
  27416. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27417. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27418. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27419. serializationObject.uv5s._updatable = true;
  27420. }
  27421. }
  27422. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27423. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27424. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27425. serializationObject.uv6s._updatable = true;
  27426. }
  27427. }
  27428. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27429. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27430. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27431. serializationObject.colors._updatable = true;
  27432. }
  27433. }
  27434. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27435. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27436. serializationObject.matricesIndices._isExpanded = true;
  27437. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27438. serializationObject.matricesIndices._updatable = true;
  27439. }
  27440. }
  27441. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27442. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27443. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27444. serializationObject.matricesWeights._updatable = true;
  27445. }
  27446. }
  27447. serializationObject.indices = this.toNumberArray(this.getIndices());
  27448. return serializationObject;
  27449. };
  27450. // Statics
  27451. Geometry.ExtractFromMesh = function (mesh, id) {
  27452. var geometry = mesh._geometry;
  27453. if (!geometry) {
  27454. return null;
  27455. }
  27456. return geometry.copy(id);
  27457. };
  27458. /**
  27459. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27460. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27461. * Be aware Math.random() could cause collisions, but:
  27462. * "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"
  27463. */
  27464. Geometry.RandomId = function () {
  27465. return BABYLON.Tools.RandomId();
  27466. };
  27467. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27468. var scene = mesh.getScene();
  27469. // Geometry
  27470. var geometryId = parsedGeometry.geometryId;
  27471. if (geometryId) {
  27472. var geometry = scene.getGeometryByID(geometryId);
  27473. if (geometry) {
  27474. geometry.applyToMesh(mesh);
  27475. }
  27476. }
  27477. else if (parsedGeometry instanceof ArrayBuffer) {
  27478. var binaryInfo = mesh._binaryInfo;
  27479. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27480. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27481. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27482. }
  27483. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27484. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27485. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27486. }
  27487. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27488. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27489. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27490. }
  27491. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27492. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27493. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27494. }
  27495. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27496. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27497. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27498. }
  27499. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27500. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27501. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27502. }
  27503. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27504. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27505. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27506. }
  27507. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27508. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27509. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27510. }
  27511. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27512. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27513. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27514. }
  27515. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27516. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27517. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27518. }
  27519. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27520. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27521. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27522. }
  27523. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27524. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27525. mesh.setIndices(indicesData);
  27526. }
  27527. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27528. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27529. mesh.subMeshes = [];
  27530. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27531. var materialIndex = subMeshesData[(i * 5) + 0];
  27532. var verticesStart = subMeshesData[(i * 5) + 1];
  27533. var verticesCount = subMeshesData[(i * 5) + 2];
  27534. var indexStart = subMeshesData[(i * 5) + 3];
  27535. var indexCount = subMeshesData[(i * 5) + 4];
  27536. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27537. }
  27538. }
  27539. }
  27540. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27541. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27542. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27543. if (parsedGeometry.uvs) {
  27544. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27545. }
  27546. if (parsedGeometry.uvs2) {
  27547. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27548. }
  27549. if (parsedGeometry.uvs3) {
  27550. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27551. }
  27552. if (parsedGeometry.uvs4) {
  27553. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27554. }
  27555. if (parsedGeometry.uvs5) {
  27556. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27557. }
  27558. if (parsedGeometry.uvs6) {
  27559. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27560. }
  27561. if (parsedGeometry.colors) {
  27562. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27563. }
  27564. if (parsedGeometry.matricesIndices) {
  27565. if (!parsedGeometry.matricesIndices._isExpanded) {
  27566. var floatIndices = [];
  27567. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27568. var matricesIndex = parsedGeometry.matricesIndices[i];
  27569. floatIndices.push(matricesIndex & 0x000000FF);
  27570. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27571. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27572. floatIndices.push(matricesIndex >> 24);
  27573. }
  27574. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27575. }
  27576. else {
  27577. delete parsedGeometry.matricesIndices._isExpanded;
  27578. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27579. }
  27580. }
  27581. if (parsedGeometry.matricesIndicesExtra) {
  27582. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27583. var floatIndices = [];
  27584. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27585. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27586. floatIndices.push(matricesIndex & 0x000000FF);
  27587. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27588. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27589. floatIndices.push(matricesIndex >> 24);
  27590. }
  27591. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27592. }
  27593. else {
  27594. delete parsedGeometry.matricesIndices._isExpanded;
  27595. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27596. }
  27597. }
  27598. if (parsedGeometry.matricesWeights) {
  27599. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27600. }
  27601. if (parsedGeometry.matricesWeightsExtra) {
  27602. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27603. }
  27604. mesh.setIndices(parsedGeometry.indices);
  27605. }
  27606. // SubMeshes
  27607. if (parsedGeometry.subMeshes) {
  27608. mesh.subMeshes = [];
  27609. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27610. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27611. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27612. }
  27613. }
  27614. // Flat shading
  27615. if (mesh._shouldGenerateFlatShading) {
  27616. mesh.convertToFlatShadedMesh();
  27617. delete mesh._shouldGenerateFlatShading;
  27618. }
  27619. // Update
  27620. mesh.computeWorldMatrix(true);
  27621. // Octree
  27622. if (scene['_selectionOctree']) {
  27623. scene['_selectionOctree'].addMesh(mesh);
  27624. }
  27625. };
  27626. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27627. if (scene.getGeometryByID(parsedVertexData.id)) {
  27628. return null; // null since geometry could be something else than a box...
  27629. }
  27630. var geometry = new Geometry(parsedVertexData.id, scene);
  27631. if (BABYLON.Tags) {
  27632. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27633. }
  27634. if (parsedVertexData.delayLoadingFile) {
  27635. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27636. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27637. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27638. geometry._delayInfo = [];
  27639. if (parsedVertexData.hasUVs) {
  27640. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27641. }
  27642. if (parsedVertexData.hasUVs2) {
  27643. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27644. }
  27645. if (parsedVertexData.hasUVs3) {
  27646. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27647. }
  27648. if (parsedVertexData.hasUVs4) {
  27649. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27650. }
  27651. if (parsedVertexData.hasUVs5) {
  27652. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27653. }
  27654. if (parsedVertexData.hasUVs6) {
  27655. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27656. }
  27657. if (parsedVertexData.hasColors) {
  27658. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27659. }
  27660. if (parsedVertexData.hasMatricesIndices) {
  27661. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27662. }
  27663. if (parsedVertexData.hasMatricesWeights) {
  27664. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27665. }
  27666. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27667. }
  27668. else {
  27669. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27670. }
  27671. scene.pushGeometry(geometry, true);
  27672. return geometry;
  27673. };
  27674. return Geometry;
  27675. }());
  27676. BABYLON.Geometry = Geometry;
  27677. /////// Primitives //////////////////////////////////////////////
  27678. (function (Geometry) {
  27679. var Primitives;
  27680. (function (Primitives) {
  27681. /// Abstract class
  27682. var _Primitive = (function (_super) {
  27683. __extends(_Primitive, _super);
  27684. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27685. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27686. _this._canBeRegenerated = _canBeRegenerated;
  27687. _this._beingRegenerated = true;
  27688. _this.regenerate();
  27689. _this._beingRegenerated = false;
  27690. return _this;
  27691. }
  27692. _Primitive.prototype.canBeRegenerated = function () {
  27693. return this._canBeRegenerated;
  27694. };
  27695. _Primitive.prototype.regenerate = function () {
  27696. if (!this._canBeRegenerated) {
  27697. return;
  27698. }
  27699. this._beingRegenerated = true;
  27700. this.setAllVerticesData(this._regenerateVertexData(), false);
  27701. this._beingRegenerated = false;
  27702. };
  27703. _Primitive.prototype.asNewGeometry = function (id) {
  27704. return _super.prototype.copy.call(this, id);
  27705. };
  27706. // overrides
  27707. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27708. if (!this._beingRegenerated) {
  27709. return;
  27710. }
  27711. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27712. };
  27713. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27714. if (!this._beingRegenerated) {
  27715. return;
  27716. }
  27717. _super.prototype.setVerticesData.call(this, kind, data, false);
  27718. };
  27719. // to override
  27720. // protected
  27721. _Primitive.prototype._regenerateVertexData = function () {
  27722. throw new Error("Abstract method");
  27723. };
  27724. _Primitive.prototype.copy = function (id) {
  27725. throw new Error("Must be overriden in sub-classes.");
  27726. };
  27727. _Primitive.prototype.serialize = function () {
  27728. var serializationObject = _super.prototype.serialize.call(this);
  27729. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27730. return serializationObject;
  27731. };
  27732. return _Primitive;
  27733. }(Geometry));
  27734. Primitives._Primitive = _Primitive;
  27735. var Ribbon = (function (_super) {
  27736. __extends(Ribbon, _super);
  27737. // Members
  27738. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27739. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27740. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27741. _this.pathArray = pathArray;
  27742. _this.closeArray = closeArray;
  27743. _this.closePath = closePath;
  27744. _this.offset = offset;
  27745. _this.side = side;
  27746. return _this;
  27747. }
  27748. Ribbon.prototype._regenerateVertexData = function () {
  27749. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27750. };
  27751. Ribbon.prototype.copy = function (id) {
  27752. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27753. };
  27754. return Ribbon;
  27755. }(_Primitive));
  27756. Primitives.Ribbon = Ribbon;
  27757. var Box = (function (_super) {
  27758. __extends(Box, _super);
  27759. // Members
  27760. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27761. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27762. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27763. _this.size = size;
  27764. _this.side = side;
  27765. return _this;
  27766. }
  27767. Box.prototype._regenerateVertexData = function () {
  27768. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27769. };
  27770. Box.prototype.copy = function (id) {
  27771. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27772. };
  27773. Box.prototype.serialize = function () {
  27774. var serializationObject = _super.prototype.serialize.call(this);
  27775. serializationObject.size = this.size;
  27776. return serializationObject;
  27777. };
  27778. Box.Parse = function (parsedBox, scene) {
  27779. if (scene.getGeometryByID(parsedBox.id)) {
  27780. return null; // null since geometry could be something else than a box...
  27781. }
  27782. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27783. if (BABYLON.Tags) {
  27784. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27785. }
  27786. scene.pushGeometry(box, true);
  27787. return box;
  27788. };
  27789. return Box;
  27790. }(_Primitive));
  27791. Primitives.Box = Box;
  27792. var Sphere = (function (_super) {
  27793. __extends(Sphere, _super);
  27794. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27795. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27796. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27797. _this.segments = segments;
  27798. _this.diameter = diameter;
  27799. _this.side = side;
  27800. return _this;
  27801. }
  27802. Sphere.prototype._regenerateVertexData = function () {
  27803. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27804. };
  27805. Sphere.prototype.copy = function (id) {
  27806. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27807. };
  27808. Sphere.prototype.serialize = function () {
  27809. var serializationObject = _super.prototype.serialize.call(this);
  27810. serializationObject.segments = this.segments;
  27811. serializationObject.diameter = this.diameter;
  27812. return serializationObject;
  27813. };
  27814. Sphere.Parse = function (parsedSphere, scene) {
  27815. if (scene.getGeometryByID(parsedSphere.id)) {
  27816. return null; // null since geometry could be something else than a sphere...
  27817. }
  27818. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27819. if (BABYLON.Tags) {
  27820. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27821. }
  27822. scene.pushGeometry(sphere, true);
  27823. return sphere;
  27824. };
  27825. return Sphere;
  27826. }(_Primitive));
  27827. Primitives.Sphere = Sphere;
  27828. var Disc = (function (_super) {
  27829. __extends(Disc, _super);
  27830. // Members
  27831. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27832. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27833. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27834. _this.radius = radius;
  27835. _this.tessellation = tessellation;
  27836. _this.side = side;
  27837. return _this;
  27838. }
  27839. Disc.prototype._regenerateVertexData = function () {
  27840. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27841. };
  27842. Disc.prototype.copy = function (id) {
  27843. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27844. };
  27845. return Disc;
  27846. }(_Primitive));
  27847. Primitives.Disc = Disc;
  27848. var Cylinder = (function (_super) {
  27849. __extends(Cylinder, _super);
  27850. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27851. if (subdivisions === void 0) { subdivisions = 1; }
  27852. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27853. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27854. _this.height = height;
  27855. _this.diameterTop = diameterTop;
  27856. _this.diameterBottom = diameterBottom;
  27857. _this.tessellation = tessellation;
  27858. _this.subdivisions = subdivisions;
  27859. _this.side = side;
  27860. return _this;
  27861. }
  27862. Cylinder.prototype._regenerateVertexData = function () {
  27863. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27864. };
  27865. Cylinder.prototype.copy = function (id) {
  27866. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27867. };
  27868. Cylinder.prototype.serialize = function () {
  27869. var serializationObject = _super.prototype.serialize.call(this);
  27870. serializationObject.height = this.height;
  27871. serializationObject.diameterTop = this.diameterTop;
  27872. serializationObject.diameterBottom = this.diameterBottom;
  27873. serializationObject.tessellation = this.tessellation;
  27874. return serializationObject;
  27875. };
  27876. Cylinder.Parse = function (parsedCylinder, scene) {
  27877. if (scene.getGeometryByID(parsedCylinder.id)) {
  27878. return null; // null since geometry could be something else than a cylinder...
  27879. }
  27880. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27881. if (BABYLON.Tags) {
  27882. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27883. }
  27884. scene.pushGeometry(cylinder, true);
  27885. return cylinder;
  27886. };
  27887. return Cylinder;
  27888. }(_Primitive));
  27889. Primitives.Cylinder = Cylinder;
  27890. var Torus = (function (_super) {
  27891. __extends(Torus, _super);
  27892. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27893. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27894. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27895. _this.diameter = diameter;
  27896. _this.thickness = thickness;
  27897. _this.tessellation = tessellation;
  27898. _this.side = side;
  27899. return _this;
  27900. }
  27901. Torus.prototype._regenerateVertexData = function () {
  27902. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27903. };
  27904. Torus.prototype.copy = function (id) {
  27905. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27906. };
  27907. Torus.prototype.serialize = function () {
  27908. var serializationObject = _super.prototype.serialize.call(this);
  27909. serializationObject.diameter = this.diameter;
  27910. serializationObject.thickness = this.thickness;
  27911. serializationObject.tessellation = this.tessellation;
  27912. return serializationObject;
  27913. };
  27914. Torus.Parse = function (parsedTorus, scene) {
  27915. if (scene.getGeometryByID(parsedTorus.id)) {
  27916. return null; // null since geometry could be something else than a torus...
  27917. }
  27918. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27919. if (BABYLON.Tags) {
  27920. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27921. }
  27922. scene.pushGeometry(torus, true);
  27923. return torus;
  27924. };
  27925. return Torus;
  27926. }(_Primitive));
  27927. Primitives.Torus = Torus;
  27928. var Ground = (function (_super) {
  27929. __extends(Ground, _super);
  27930. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27931. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27932. _this.width = width;
  27933. _this.height = height;
  27934. _this.subdivisions = subdivisions;
  27935. return _this;
  27936. }
  27937. Ground.prototype._regenerateVertexData = function () {
  27938. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27939. };
  27940. Ground.prototype.copy = function (id) {
  27941. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27942. };
  27943. Ground.prototype.serialize = function () {
  27944. var serializationObject = _super.prototype.serialize.call(this);
  27945. serializationObject.width = this.width;
  27946. serializationObject.height = this.height;
  27947. serializationObject.subdivisions = this.subdivisions;
  27948. return serializationObject;
  27949. };
  27950. Ground.Parse = function (parsedGround, scene) {
  27951. if (scene.getGeometryByID(parsedGround.id)) {
  27952. return null; // null since geometry could be something else than a ground...
  27953. }
  27954. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27955. if (BABYLON.Tags) {
  27956. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27957. }
  27958. scene.pushGeometry(ground, true);
  27959. return ground;
  27960. };
  27961. return Ground;
  27962. }(_Primitive));
  27963. Primitives.Ground = Ground;
  27964. var TiledGround = (function (_super) {
  27965. __extends(TiledGround, _super);
  27966. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27967. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27968. _this.xmin = xmin;
  27969. _this.zmin = zmin;
  27970. _this.xmax = xmax;
  27971. _this.zmax = zmax;
  27972. _this.subdivisions = subdivisions;
  27973. _this.precision = precision;
  27974. return _this;
  27975. }
  27976. TiledGround.prototype._regenerateVertexData = function () {
  27977. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27978. };
  27979. TiledGround.prototype.copy = function (id) {
  27980. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27981. };
  27982. return TiledGround;
  27983. }(_Primitive));
  27984. Primitives.TiledGround = TiledGround;
  27985. var Plane = (function (_super) {
  27986. __extends(Plane, _super);
  27987. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27988. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27989. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27990. _this.size = size;
  27991. _this.side = side;
  27992. return _this;
  27993. }
  27994. Plane.prototype._regenerateVertexData = function () {
  27995. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27996. };
  27997. Plane.prototype.copy = function (id) {
  27998. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27999. };
  28000. Plane.prototype.serialize = function () {
  28001. var serializationObject = _super.prototype.serialize.call(this);
  28002. serializationObject.size = this.size;
  28003. return serializationObject;
  28004. };
  28005. Plane.Parse = function (parsedPlane, scene) {
  28006. if (scene.getGeometryByID(parsedPlane.id)) {
  28007. return null; // null since geometry could be something else than a ground...
  28008. }
  28009. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28010. if (BABYLON.Tags) {
  28011. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28012. }
  28013. scene.pushGeometry(plane, true);
  28014. return plane;
  28015. };
  28016. return Plane;
  28017. }(_Primitive));
  28018. Primitives.Plane = Plane;
  28019. var TorusKnot = (function (_super) {
  28020. __extends(TorusKnot, _super);
  28021. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28022. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28023. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28024. _this.radius = radius;
  28025. _this.tube = tube;
  28026. _this.radialSegments = radialSegments;
  28027. _this.tubularSegments = tubularSegments;
  28028. _this.p = p;
  28029. _this.q = q;
  28030. _this.side = side;
  28031. return _this;
  28032. }
  28033. TorusKnot.prototype._regenerateVertexData = function () {
  28034. 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 });
  28035. };
  28036. TorusKnot.prototype.copy = function (id) {
  28037. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28038. };
  28039. TorusKnot.prototype.serialize = function () {
  28040. var serializationObject = _super.prototype.serialize.call(this);
  28041. serializationObject.radius = this.radius;
  28042. serializationObject.tube = this.tube;
  28043. serializationObject.radialSegments = this.radialSegments;
  28044. serializationObject.tubularSegments = this.tubularSegments;
  28045. serializationObject.p = this.p;
  28046. serializationObject.q = this.q;
  28047. return serializationObject;
  28048. };
  28049. ;
  28050. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28051. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28052. return null; // null since geometry could be something else than a ground...
  28053. }
  28054. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28055. if (BABYLON.Tags) {
  28056. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28057. }
  28058. scene.pushGeometry(torusKnot, true);
  28059. return torusKnot;
  28060. };
  28061. return TorusKnot;
  28062. }(_Primitive));
  28063. Primitives.TorusKnot = TorusKnot;
  28064. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28065. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28066. })(BABYLON || (BABYLON = {}));
  28067. //# sourceMappingURL=babylon.geometry.js.map
  28068. var BABYLON;
  28069. (function (BABYLON) {
  28070. var PostProcessManager = (function () {
  28071. function PostProcessManager(scene) {
  28072. this._vertexBuffers = {};
  28073. this._scene = scene;
  28074. }
  28075. PostProcessManager.prototype._prepareBuffers = function () {
  28076. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28077. return;
  28078. }
  28079. // VBO
  28080. var vertices = [];
  28081. vertices.push(1, 1);
  28082. vertices.push(-1, 1);
  28083. vertices.push(-1, -1);
  28084. vertices.push(1, -1);
  28085. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28086. // Indices
  28087. var indices = [];
  28088. indices.push(0);
  28089. indices.push(1);
  28090. indices.push(2);
  28091. indices.push(0);
  28092. indices.push(2);
  28093. indices.push(3);
  28094. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28095. };
  28096. // Methods
  28097. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28098. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28099. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28100. return false;
  28101. }
  28102. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28103. return true;
  28104. };
  28105. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28106. var engine = this._scene.getEngine();
  28107. for (var index = 0; index < postProcesses.length; index++) {
  28108. if (index < postProcesses.length - 1) {
  28109. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28110. }
  28111. else {
  28112. if (targetTexture) {
  28113. engine.bindFramebuffer(targetTexture);
  28114. }
  28115. else {
  28116. engine.restoreDefaultFramebuffer();
  28117. }
  28118. }
  28119. var pp = postProcesses[index];
  28120. var effect = pp.apply();
  28121. if (effect) {
  28122. pp.onBeforeRenderObservable.notifyObservers(effect);
  28123. // VBOs
  28124. this._prepareBuffers();
  28125. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28126. // Draw order
  28127. engine.draw(true, 0, 6);
  28128. pp.onAfterRenderObservable.notifyObservers(effect);
  28129. }
  28130. }
  28131. // Restore depth buffer
  28132. engine.setDepthBuffer(true);
  28133. engine.setDepthWrite(true);
  28134. };
  28135. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28136. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28137. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28138. return;
  28139. }
  28140. var engine = this._scene.getEngine();
  28141. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28142. if (index < len - 1) {
  28143. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28144. }
  28145. else {
  28146. if (targetTexture) {
  28147. engine.bindFramebuffer(targetTexture, faceIndex);
  28148. }
  28149. else {
  28150. engine.restoreDefaultFramebuffer();
  28151. }
  28152. }
  28153. if (doNotPresent) {
  28154. break;
  28155. }
  28156. var pp = postProcesses[index];
  28157. var effect = pp.apply();
  28158. if (effect) {
  28159. pp.onBeforeRenderObservable.notifyObservers(effect);
  28160. // VBOs
  28161. this._prepareBuffers();
  28162. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28163. // Draw order
  28164. engine.draw(true, 0, 6);
  28165. pp.onAfterRenderObservable.notifyObservers(effect);
  28166. }
  28167. }
  28168. // Restore states
  28169. engine.setDepthBuffer(true);
  28170. engine.setDepthWrite(true);
  28171. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28172. };
  28173. PostProcessManager.prototype.dispose = function () {
  28174. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28175. if (buffer) {
  28176. buffer.dispose();
  28177. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28178. }
  28179. if (this._indexBuffer) {
  28180. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28181. this._indexBuffer = null;
  28182. }
  28183. };
  28184. return PostProcessManager;
  28185. }());
  28186. BABYLON.PostProcessManager = PostProcessManager;
  28187. })(BABYLON || (BABYLON = {}));
  28188. //# sourceMappingURL=babylon.postProcessManager.js.map
  28189. var BABYLON;
  28190. (function (BABYLON) {
  28191. var StandardMaterialDefines = (function (_super) {
  28192. __extends(StandardMaterialDefines, _super);
  28193. function StandardMaterialDefines() {
  28194. var _this = _super.call(this) || this;
  28195. _this.DIFFUSE = false;
  28196. _this.AMBIENT = false;
  28197. _this.OPACITY = false;
  28198. _this.OPACITYRGB = false;
  28199. _this.REFLECTION = false;
  28200. _this.EMISSIVE = false;
  28201. _this.SPECULAR = false;
  28202. _this.BUMP = false;
  28203. _this.PARALLAX = false;
  28204. _this.PARALLAXOCCLUSION = false;
  28205. _this.SPECULAROVERALPHA = false;
  28206. _this.CLIPPLANE = false;
  28207. _this.ALPHATEST = false;
  28208. _this.ALPHAFROMDIFFUSE = false;
  28209. _this.POINTSIZE = false;
  28210. _this.FOG = false;
  28211. _this.SPECULARTERM = false;
  28212. _this.DIFFUSEFRESNEL = false;
  28213. _this.OPACITYFRESNEL = false;
  28214. _this.REFLECTIONFRESNEL = false;
  28215. _this.REFRACTIONFRESNEL = false;
  28216. _this.EMISSIVEFRESNEL = false;
  28217. _this.FRESNEL = false;
  28218. _this.NORMAL = false;
  28219. _this.UV1 = false;
  28220. _this.UV2 = false;
  28221. _this.VERTEXCOLOR = false;
  28222. _this.VERTEXALPHA = false;
  28223. _this.NUM_BONE_INFLUENCERS = 0;
  28224. _this.BonesPerMesh = 0;
  28225. _this.INSTANCES = false;
  28226. _this.GLOSSINESS = false;
  28227. _this.ROUGHNESS = false;
  28228. _this.EMISSIVEASILLUMINATION = false;
  28229. _this.LINKEMISSIVEWITHDIFFUSE = false;
  28230. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  28231. _this.LIGHTMAP = false;
  28232. _this.USELIGHTMAPASSHADOWMAP = false;
  28233. _this.REFLECTIONMAP_3D = false;
  28234. _this.REFLECTIONMAP_SPHERICAL = false;
  28235. _this.REFLECTIONMAP_PLANAR = false;
  28236. _this.REFLECTIONMAP_CUBIC = false;
  28237. _this.REFLECTIONMAP_PROJECTION = false;
  28238. _this.REFLECTIONMAP_SKYBOX = false;
  28239. _this.REFLECTIONMAP_EXPLICIT = false;
  28240. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  28241. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  28242. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  28243. _this.INVERTCUBICMAP = false;
  28244. _this.LOGARITHMICDEPTH = false;
  28245. _this.REFRACTION = false;
  28246. _this.REFRACTIONMAP_3D = false;
  28247. _this.REFLECTIONOVERALPHA = false;
  28248. _this.INVERTNORMALMAPX = false;
  28249. _this.INVERTNORMALMAPY = false;
  28250. _this.TWOSIDEDLIGHTING = false;
  28251. _this.SHADOWFLOAT = false;
  28252. _this.CAMERACOLORGRADING = false;
  28253. _this.CAMERACOLORCURVES = false;
  28254. _this.MORPHTARGETS = false;
  28255. _this.MORPHTARGETS_NORMAL = false;
  28256. _this.MORPHTARGETS_TANGENT = false;
  28257. _this.NUM_MORPH_INFLUENCERS = 0;
  28258. _this.USERIGHTHANDEDSYSTEM = false;
  28259. _this.rebuild();
  28260. return _this;
  28261. }
  28262. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  28263. var modes = [
  28264. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  28265. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  28266. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  28267. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  28268. ];
  28269. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  28270. var mode = modes_1[_i];
  28271. this[mode] = (mode === modeToEnable);
  28272. }
  28273. };
  28274. return StandardMaterialDefines;
  28275. }(BABYLON.MaterialDefines));
  28276. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  28277. var StandardMaterial = (function (_super) {
  28278. __extends(StandardMaterial, _super);
  28279. function StandardMaterial(name, scene) {
  28280. var _this = _super.call(this, name, scene) || this;
  28281. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  28282. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  28283. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  28284. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  28285. _this.specularPower = 64;
  28286. _this._useAlphaFromDiffuseTexture = false;
  28287. _this._useEmissiveAsIllumination = false;
  28288. _this._linkEmissiveWithDiffuse = false;
  28289. _this._useSpecularOverAlpha = false;
  28290. _this._useReflectionOverAlpha = false;
  28291. _this._disableLighting = false;
  28292. _this._useParallax = false;
  28293. _this._useParallaxOcclusion = false;
  28294. _this.parallaxScaleBias = 0.05;
  28295. _this._roughness = 0;
  28296. _this.indexOfRefraction = 0.98;
  28297. _this.invertRefractionY = true;
  28298. _this._useLightmapAsShadowmap = false;
  28299. _this._useReflectionFresnelFromSpecular = false;
  28300. _this._useGlossinessFromSpecularMapAlpha = false;
  28301. _this._maxSimultaneousLights = 4;
  28302. /**
  28303. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  28304. */
  28305. _this._invertNormalMapX = false;
  28306. /**
  28307. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  28308. */
  28309. _this._invertNormalMapY = false;
  28310. /**
  28311. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  28312. */
  28313. _this._twoSidedLighting = false;
  28314. /**
  28315. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  28316. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  28317. * 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;
  28318. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  28319. */
  28320. _this._cameraColorCurves = null;
  28321. _this._renderTargets = new BABYLON.SmartArray(16);
  28322. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  28323. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  28324. _this.getRenderTargetTextures = function () {
  28325. _this._renderTargets.reset();
  28326. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  28327. _this._renderTargets.push(_this._reflectionTexture);
  28328. }
  28329. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  28330. _this._renderTargets.push(_this._refractionTexture);
  28331. }
  28332. return _this._renderTargets;
  28333. };
  28334. return _this;
  28335. }
  28336. StandardMaterial.prototype.getClassName = function () {
  28337. return "StandardMaterial";
  28338. };
  28339. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  28340. get: function () {
  28341. return this._useLogarithmicDepth;
  28342. },
  28343. set: function (value) {
  28344. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  28345. this._markAllSubMeshesAsMiscDirty();
  28346. },
  28347. enumerable: true,
  28348. configurable: true
  28349. });
  28350. StandardMaterial.prototype.needAlphaBlending = function () {
  28351. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  28352. };
  28353. StandardMaterial.prototype.needAlphaTesting = function () {
  28354. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  28355. };
  28356. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  28357. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  28358. };
  28359. StandardMaterial.prototype.getAlphaTestTexture = function () {
  28360. return this._diffuseTexture;
  28361. };
  28362. /**
  28363. * Child classes can use it to update shaders
  28364. */
  28365. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28366. if (this.isFrozen) {
  28367. if (this._wasPreviouslyReady && subMesh.effect) {
  28368. return true;
  28369. }
  28370. }
  28371. if (!subMesh._materialDefines) {
  28372. subMesh._materialDefines = new StandardMaterialDefines();
  28373. }
  28374. var scene = this.getScene();
  28375. var defines = subMesh._materialDefines;
  28376. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  28377. if (defines._renderId === scene.getRenderId()) {
  28378. return true;
  28379. }
  28380. }
  28381. var engine = scene.getEngine();
  28382. // Lights
  28383. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  28384. // Textures
  28385. if (defines._areTexturesDirty) {
  28386. defines._needUVs = false;
  28387. if (scene.texturesEnabled) {
  28388. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28389. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  28390. return false;
  28391. }
  28392. else {
  28393. defines._needUVs = true;
  28394. defines.DIFFUSE = true;
  28395. }
  28396. }
  28397. else {
  28398. defines.DIFFUSE = false;
  28399. }
  28400. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28401. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  28402. return false;
  28403. }
  28404. else {
  28405. defines._needUVs = true;
  28406. defines.AMBIENT = true;
  28407. }
  28408. }
  28409. else {
  28410. defines.AMBIENT = false;
  28411. }
  28412. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28413. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  28414. return false;
  28415. }
  28416. else {
  28417. defines._needUVs = true;
  28418. defines.OPACITY = true;
  28419. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  28420. }
  28421. }
  28422. else {
  28423. defines.OPACITY = false;
  28424. }
  28425. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28426. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  28427. return false;
  28428. }
  28429. else {
  28430. defines._needNormals = true;
  28431. defines.REFLECTION = true;
  28432. defines.ROUGHNESS = (this._roughness > 0);
  28433. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  28434. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  28435. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  28436. switch (this._reflectionTexture.coordinatesMode) {
  28437. case BABYLON.Texture.CUBIC_MODE:
  28438. case BABYLON.Texture.INVCUBIC_MODE:
  28439. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  28440. break;
  28441. case BABYLON.Texture.EXPLICIT_MODE:
  28442. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  28443. break;
  28444. case BABYLON.Texture.PLANAR_MODE:
  28445. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  28446. break;
  28447. case BABYLON.Texture.PROJECTION_MODE:
  28448. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  28449. break;
  28450. case BABYLON.Texture.SKYBOX_MODE:
  28451. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  28452. break;
  28453. case BABYLON.Texture.SPHERICAL_MODE:
  28454. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  28455. break;
  28456. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28457. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  28458. break;
  28459. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28460. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  28461. break;
  28462. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28463. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  28464. break;
  28465. }
  28466. }
  28467. }
  28468. else {
  28469. defines.REFLECTION = false;
  28470. }
  28471. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28472. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  28473. return false;
  28474. }
  28475. else {
  28476. defines._needUVs = true;
  28477. defines.EMISSIVE = true;
  28478. }
  28479. }
  28480. else {
  28481. defines.EMISSIVE = false;
  28482. }
  28483. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28484. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  28485. return false;
  28486. }
  28487. else {
  28488. defines._needUVs = true;
  28489. defines.LIGHTMAP = true;
  28490. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  28491. }
  28492. }
  28493. else {
  28494. defines.LIGHTMAP = false;
  28495. }
  28496. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28497. if (!this._specularTexture.isReadyOrNotBlocking()) {
  28498. return false;
  28499. }
  28500. else {
  28501. defines._needUVs = true;
  28502. defines.SPECULAR = true;
  28503. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  28504. }
  28505. }
  28506. else {
  28507. defines.SPECULAR = false;
  28508. }
  28509. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  28510. // Bump texure can not be none blocking.
  28511. if (!this._bumpTexture.isReady()) {
  28512. return false;
  28513. }
  28514. else {
  28515. defines._needUVs = true;
  28516. defines.BUMP = true;
  28517. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  28518. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  28519. defines.PARALLAX = this._useParallax;
  28520. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  28521. }
  28522. }
  28523. else {
  28524. defines.BUMP = false;
  28525. }
  28526. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28527. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  28528. return false;
  28529. }
  28530. else {
  28531. defines._needUVs = true;
  28532. defines.REFRACTION = true;
  28533. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  28534. }
  28535. }
  28536. else {
  28537. defines.REFRACTION = false;
  28538. }
  28539. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  28540. // Camera Color Grading can not be none blocking.
  28541. if (!this._cameraColorGradingTexture.isReady()) {
  28542. return false;
  28543. }
  28544. else {
  28545. defines.CAMERACOLORGRADING = true;
  28546. }
  28547. }
  28548. else {
  28549. defines.CAMERACOLORGRADING = false;
  28550. }
  28551. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  28552. }
  28553. else {
  28554. defines.DIFFUSE = false;
  28555. defines.AMBIENT = false;
  28556. defines.OPACITY = false;
  28557. defines.REFLECTION = false;
  28558. defines.EMISSIVE = false;
  28559. defines.LIGHTMAP = false;
  28560. defines.BUMP = false;
  28561. defines.REFRACTION = false;
  28562. defines.CAMERACOLORGRADING = false;
  28563. }
  28564. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  28565. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  28566. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  28567. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  28568. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  28569. }
  28570. if (defines._areFresnelDirty) {
  28571. if (StandardMaterial.FresnelEnabled) {
  28572. // Fresnel
  28573. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  28574. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  28575. this._reflectionFresnelParameters) {
  28576. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  28577. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  28578. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  28579. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  28580. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  28581. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  28582. defines._needNormals = true;
  28583. defines.FRESNEL = true;
  28584. }
  28585. }
  28586. else {
  28587. defines.FRESNEL = false;
  28588. }
  28589. }
  28590. // Misc.
  28591. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  28592. // Attribs
  28593. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  28594. // Values that need to be evaluated on every frame
  28595. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  28596. if (scene._mirroredCameraPosition && defines.BUMP) {
  28597. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  28598. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  28599. defines.markAsUnprocessed();
  28600. }
  28601. // Get correct effect
  28602. if (defines.isDirty) {
  28603. defines.markAsProcessed();
  28604. scene.resetCachedMaterial();
  28605. // Fallbacks
  28606. var fallbacks = new BABYLON.EffectFallbacks();
  28607. if (defines.REFLECTION) {
  28608. fallbacks.addFallback(0, "REFLECTION");
  28609. }
  28610. if (defines.SPECULAR) {
  28611. fallbacks.addFallback(0, "SPECULAR");
  28612. }
  28613. if (defines.BUMP) {
  28614. fallbacks.addFallback(0, "BUMP");
  28615. }
  28616. if (defines.PARALLAX) {
  28617. fallbacks.addFallback(1, "PARALLAX");
  28618. }
  28619. if (defines.PARALLAXOCCLUSION) {
  28620. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  28621. }
  28622. if (defines.SPECULAROVERALPHA) {
  28623. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  28624. }
  28625. if (defines.FOG) {
  28626. fallbacks.addFallback(1, "FOG");
  28627. }
  28628. if (defines.POINTSIZE) {
  28629. fallbacks.addFallback(0, "POINTSIZE");
  28630. }
  28631. if (defines.LOGARITHMICDEPTH) {
  28632. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  28633. }
  28634. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  28635. if (defines.SPECULARTERM) {
  28636. fallbacks.addFallback(0, "SPECULARTERM");
  28637. }
  28638. if (defines.DIFFUSEFRESNEL) {
  28639. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  28640. }
  28641. if (defines.OPACITYFRESNEL) {
  28642. fallbacks.addFallback(2, "OPACITYFRESNEL");
  28643. }
  28644. if (defines.REFLECTIONFRESNEL) {
  28645. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  28646. }
  28647. if (defines.EMISSIVEFRESNEL) {
  28648. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  28649. }
  28650. if (defines.FRESNEL) {
  28651. fallbacks.addFallback(4, "FRESNEL");
  28652. }
  28653. //Attributes
  28654. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28655. if (defines.NORMAL) {
  28656. attribs.push(BABYLON.VertexBuffer.NormalKind);
  28657. }
  28658. if (defines.UV1) {
  28659. attribs.push(BABYLON.VertexBuffer.UVKind);
  28660. }
  28661. if (defines.UV2) {
  28662. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28663. }
  28664. if (defines.VERTEXCOLOR) {
  28665. attribs.push(BABYLON.VertexBuffer.ColorKind);
  28666. }
  28667. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  28668. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  28669. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  28670. var shaderName = "default";
  28671. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  28672. "vFogInfos", "vFogColor", "pointSize",
  28673. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  28674. "mBones",
  28675. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  28676. "depthValues",
  28677. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  28678. "logarithmicDepthConstant"
  28679. ];
  28680. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  28681. var uniformBuffers = ["Material", "Scene"];
  28682. if (defines.CAMERACOLORCURVES) {
  28683. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  28684. }
  28685. if (defines.CAMERACOLORGRADING) {
  28686. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  28687. }
  28688. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  28689. uniformsNames: uniforms,
  28690. uniformBuffersNames: uniformBuffers,
  28691. samplers: samplers,
  28692. defines: defines,
  28693. maxSimultaneousLights: this._maxSimultaneousLights
  28694. });
  28695. if (this.customShaderNameResolve) {
  28696. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  28697. }
  28698. var join = defines.toString();
  28699. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  28700. attributes: attribs,
  28701. uniformsNames: uniforms,
  28702. uniformBuffersNames: uniformBuffers,
  28703. samplers: samplers,
  28704. defines: join,
  28705. fallbacks: fallbacks,
  28706. onCompiled: this.onCompiled,
  28707. onError: this.onError,
  28708. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  28709. }, engine), defines);
  28710. this.buildUniformLayout();
  28711. }
  28712. if (!subMesh.effect.isReady()) {
  28713. return false;
  28714. }
  28715. defines._renderId = scene.getRenderId();
  28716. this._wasPreviouslyReady = true;
  28717. return true;
  28718. };
  28719. StandardMaterial.prototype.buildUniformLayout = function () {
  28720. // Order is important !
  28721. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  28722. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  28723. this._uniformBuffer.addUniform("opacityParts", 4);
  28724. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  28725. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  28726. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  28727. this._uniformBuffer.addUniform("refractionRightColor", 4);
  28728. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  28729. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  28730. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  28731. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  28732. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  28733. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  28734. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  28735. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  28736. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  28737. this._uniformBuffer.addUniform("vBumpInfos", 3);
  28738. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  28739. this._uniformBuffer.addUniform("ambientMatrix", 16);
  28740. this._uniformBuffer.addUniform("opacityMatrix", 16);
  28741. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  28742. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  28743. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  28744. this._uniformBuffer.addUniform("specularMatrix", 16);
  28745. this._uniformBuffer.addUniform("bumpMatrix", 16);
  28746. this._uniformBuffer.addUniform("refractionMatrix", 16);
  28747. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  28748. this._uniformBuffer.addUniform("vSpecularColor", 4);
  28749. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  28750. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  28751. this._uniformBuffer.addUniform("pointSize", 1);
  28752. this._uniformBuffer.create();
  28753. };
  28754. StandardMaterial.prototype.unbind = function () {
  28755. if (this._activeEffect) {
  28756. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  28757. this._activeEffect.setTexture("reflection2DSampler", null);
  28758. }
  28759. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  28760. this._activeEffect.setTexture("refraction2DSampler", null);
  28761. }
  28762. }
  28763. _super.prototype.unbind.call(this);
  28764. };
  28765. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28766. var scene = this.getScene();
  28767. var defines = subMesh._materialDefines;
  28768. if (!defines) {
  28769. return;
  28770. }
  28771. var effect = subMesh.effect;
  28772. this._activeEffect = effect;
  28773. // Matrices
  28774. this.bindOnlyWorldMatrix(world);
  28775. // Bones
  28776. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  28777. if (this._mustRebind(scene, effect, mesh.visibility)) {
  28778. this._uniformBuffer.bindToEffect(effect, "Material");
  28779. this.bindViewProjection(effect);
  28780. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  28781. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  28782. // Fresnel
  28783. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  28784. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  28785. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  28786. }
  28787. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  28788. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  28789. }
  28790. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  28791. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  28792. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  28793. }
  28794. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  28795. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  28796. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  28797. }
  28798. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28799. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  28800. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  28801. }
  28802. }
  28803. // Textures
  28804. if (scene.texturesEnabled) {
  28805. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28806. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  28807. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  28808. }
  28809. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28810. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  28811. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  28812. }
  28813. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28814. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  28815. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  28816. }
  28817. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28818. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  28819. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  28820. }
  28821. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28822. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  28823. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  28824. }
  28825. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28826. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  28827. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  28828. }
  28829. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28830. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  28831. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  28832. }
  28833. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  28834. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  28835. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  28836. }
  28837. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28838. var depth = 1.0;
  28839. if (!this._refractionTexture.isCube) {
  28840. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  28841. if (this._refractionTexture.depth) {
  28842. depth = this._refractionTexture.depth;
  28843. }
  28844. }
  28845. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  28846. }
  28847. }
  28848. // Point size
  28849. if (this.pointsCloud) {
  28850. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  28851. }
  28852. if (defines.SPECULARTERM) {
  28853. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  28854. }
  28855. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  28856. // Diffuse
  28857. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  28858. }
  28859. // Textures
  28860. if (scene.texturesEnabled) {
  28861. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28862. effect.setTexture("diffuseSampler", this._diffuseTexture);
  28863. }
  28864. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28865. effect.setTexture("ambientSampler", this._ambientTexture);
  28866. }
  28867. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28868. effect.setTexture("opacitySampler", this._opacityTexture);
  28869. }
  28870. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28871. if (this._reflectionTexture.isCube) {
  28872. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  28873. }
  28874. else {
  28875. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  28876. }
  28877. }
  28878. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28879. effect.setTexture("emissiveSampler", this._emissiveTexture);
  28880. }
  28881. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28882. effect.setTexture("lightmapSampler", this._lightmapTexture);
  28883. }
  28884. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28885. effect.setTexture("specularSampler", this._specularTexture);
  28886. }
  28887. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  28888. effect.setTexture("bumpSampler", this._bumpTexture);
  28889. }
  28890. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28891. var depth = 1.0;
  28892. if (this._refractionTexture.isCube) {
  28893. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  28894. }
  28895. else {
  28896. effect.setTexture("refraction2DSampler", this._refractionTexture);
  28897. }
  28898. }
  28899. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  28900. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  28901. }
  28902. }
  28903. // Clip plane
  28904. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  28905. // Colors
  28906. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  28907. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  28908. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  28909. }
  28910. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  28911. // Lights
  28912. if (scene.lightsEnabled && !this._disableLighting) {
  28913. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  28914. }
  28915. // View
  28916. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  28917. this.bindView(effect);
  28918. }
  28919. // Fog
  28920. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  28921. // Morph targets
  28922. if (defines.NUM_MORPH_INFLUENCERS) {
  28923. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  28924. }
  28925. // Log. depth
  28926. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  28927. // Color Curves
  28928. if (this._cameraColorCurves) {
  28929. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  28930. }
  28931. }
  28932. this._uniformBuffer.update();
  28933. this._afterBind(mesh, this._activeEffect);
  28934. };
  28935. StandardMaterial.prototype.getAnimatables = function () {
  28936. var results = [];
  28937. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  28938. results.push(this._diffuseTexture);
  28939. }
  28940. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  28941. results.push(this._ambientTexture);
  28942. }
  28943. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  28944. results.push(this._opacityTexture);
  28945. }
  28946. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  28947. results.push(this._reflectionTexture);
  28948. }
  28949. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  28950. results.push(this._emissiveTexture);
  28951. }
  28952. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  28953. results.push(this._specularTexture);
  28954. }
  28955. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  28956. results.push(this._bumpTexture);
  28957. }
  28958. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  28959. results.push(this._lightmapTexture);
  28960. }
  28961. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  28962. results.push(this._refractionTexture);
  28963. }
  28964. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  28965. results.push(this._cameraColorGradingTexture);
  28966. }
  28967. return results;
  28968. };
  28969. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28970. if (forceDisposeTextures) {
  28971. if (this._diffuseTexture) {
  28972. this._diffuseTexture.dispose();
  28973. }
  28974. if (this._ambientTexture) {
  28975. this._ambientTexture.dispose();
  28976. }
  28977. if (this._opacityTexture) {
  28978. this._opacityTexture.dispose();
  28979. }
  28980. if (this._reflectionTexture) {
  28981. this._reflectionTexture.dispose();
  28982. }
  28983. if (this._emissiveTexture) {
  28984. this._emissiveTexture.dispose();
  28985. }
  28986. if (this._specularTexture) {
  28987. this._specularTexture.dispose();
  28988. }
  28989. if (this._bumpTexture) {
  28990. this._bumpTexture.dispose();
  28991. }
  28992. if (this._lightmapTexture) {
  28993. this._lightmapTexture.dispose();
  28994. }
  28995. if (this._refractionTexture) {
  28996. this._refractionTexture.dispose();
  28997. }
  28998. if (this._cameraColorGradingTexture) {
  28999. this._cameraColorGradingTexture.dispose();
  29000. }
  29001. }
  29002. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  29003. };
  29004. StandardMaterial.prototype.clone = function (name) {
  29005. var _this = this;
  29006. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  29007. result.name = name;
  29008. result.id = name;
  29009. return result;
  29010. };
  29011. StandardMaterial.prototype.serialize = function () {
  29012. return BABYLON.SerializationHelper.Serialize(this);
  29013. };
  29014. // Statics
  29015. StandardMaterial.Parse = function (source, scene, rootUrl) {
  29016. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  29017. };
  29018. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  29019. get: function () {
  29020. return StandardMaterial._DiffuseTextureEnabled;
  29021. },
  29022. set: function (value) {
  29023. if (StandardMaterial._DiffuseTextureEnabled === value) {
  29024. return;
  29025. }
  29026. StandardMaterial._DiffuseTextureEnabled = value;
  29027. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29028. },
  29029. enumerable: true,
  29030. configurable: true
  29031. });
  29032. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  29033. get: function () {
  29034. return StandardMaterial._AmbientTextureEnabled;
  29035. },
  29036. set: function (value) {
  29037. if (StandardMaterial._AmbientTextureEnabled === value) {
  29038. return;
  29039. }
  29040. StandardMaterial._AmbientTextureEnabled = value;
  29041. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29042. },
  29043. enumerable: true,
  29044. configurable: true
  29045. });
  29046. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  29047. get: function () {
  29048. return StandardMaterial._OpacityTextureEnabled;
  29049. },
  29050. set: function (value) {
  29051. if (StandardMaterial._OpacityTextureEnabled === value) {
  29052. return;
  29053. }
  29054. StandardMaterial._OpacityTextureEnabled = value;
  29055. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29056. },
  29057. enumerable: true,
  29058. configurable: true
  29059. });
  29060. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  29061. get: function () {
  29062. return StandardMaterial._ReflectionTextureEnabled;
  29063. },
  29064. set: function (value) {
  29065. if (StandardMaterial._ReflectionTextureEnabled === value) {
  29066. return;
  29067. }
  29068. StandardMaterial._ReflectionTextureEnabled = value;
  29069. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29070. },
  29071. enumerable: true,
  29072. configurable: true
  29073. });
  29074. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  29075. get: function () {
  29076. return StandardMaterial._EmissiveTextureEnabled;
  29077. },
  29078. set: function (value) {
  29079. if (StandardMaterial._EmissiveTextureEnabled === value) {
  29080. return;
  29081. }
  29082. StandardMaterial._EmissiveTextureEnabled = value;
  29083. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29084. },
  29085. enumerable: true,
  29086. configurable: true
  29087. });
  29088. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  29089. get: function () {
  29090. return StandardMaterial._SpecularTextureEnabled;
  29091. },
  29092. set: function (value) {
  29093. if (StandardMaterial._SpecularTextureEnabled === value) {
  29094. return;
  29095. }
  29096. StandardMaterial._SpecularTextureEnabled = value;
  29097. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29098. },
  29099. enumerable: true,
  29100. configurable: true
  29101. });
  29102. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  29103. get: function () {
  29104. return StandardMaterial._BumpTextureEnabled;
  29105. },
  29106. set: function (value) {
  29107. if (StandardMaterial._BumpTextureEnabled === value) {
  29108. return;
  29109. }
  29110. StandardMaterial._BumpTextureEnabled = value;
  29111. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29112. },
  29113. enumerable: true,
  29114. configurable: true
  29115. });
  29116. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  29117. get: function () {
  29118. return StandardMaterial._LightmapTextureEnabled;
  29119. },
  29120. set: function (value) {
  29121. if (StandardMaterial._LightmapTextureEnabled === value) {
  29122. return;
  29123. }
  29124. StandardMaterial._LightmapTextureEnabled = value;
  29125. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29126. },
  29127. enumerable: true,
  29128. configurable: true
  29129. });
  29130. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  29131. get: function () {
  29132. return StandardMaterial._RefractionTextureEnabled;
  29133. },
  29134. set: function (value) {
  29135. if (StandardMaterial._RefractionTextureEnabled === value) {
  29136. return;
  29137. }
  29138. StandardMaterial._RefractionTextureEnabled = value;
  29139. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29140. },
  29141. enumerable: true,
  29142. configurable: true
  29143. });
  29144. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  29145. get: function () {
  29146. return StandardMaterial._ColorGradingTextureEnabled;
  29147. },
  29148. set: function (value) {
  29149. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  29150. return;
  29151. }
  29152. StandardMaterial._ColorGradingTextureEnabled = value;
  29153. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29154. },
  29155. enumerable: true,
  29156. configurable: true
  29157. });
  29158. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  29159. get: function () {
  29160. return StandardMaterial._FresnelEnabled;
  29161. },
  29162. set: function (value) {
  29163. if (StandardMaterial._FresnelEnabled === value) {
  29164. return;
  29165. }
  29166. StandardMaterial._FresnelEnabled = value;
  29167. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  29168. },
  29169. enumerable: true,
  29170. configurable: true
  29171. });
  29172. return StandardMaterial;
  29173. }(BABYLON.PushMaterial));
  29174. // Flags used to enable or disable a type of texture for all Standard Materials
  29175. StandardMaterial._DiffuseTextureEnabled = true;
  29176. StandardMaterial._AmbientTextureEnabled = true;
  29177. StandardMaterial._OpacityTextureEnabled = true;
  29178. StandardMaterial._ReflectionTextureEnabled = true;
  29179. StandardMaterial._EmissiveTextureEnabled = true;
  29180. StandardMaterial._SpecularTextureEnabled = true;
  29181. StandardMaterial._BumpTextureEnabled = true;
  29182. StandardMaterial._LightmapTextureEnabled = true;
  29183. StandardMaterial._RefractionTextureEnabled = true;
  29184. StandardMaterial._ColorGradingTextureEnabled = true;
  29185. StandardMaterial._FresnelEnabled = true;
  29186. __decorate([
  29187. BABYLON.serializeAsTexture("diffuseTexture")
  29188. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  29189. __decorate([
  29190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29191. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  29192. __decorate([
  29193. BABYLON.serializeAsTexture("ambientTexture")
  29194. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  29195. __decorate([
  29196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29197. ], StandardMaterial.prototype, "ambientTexture", void 0);
  29198. __decorate([
  29199. BABYLON.serializeAsTexture("opacityTexture")
  29200. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  29201. __decorate([
  29202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29203. ], StandardMaterial.prototype, "opacityTexture", void 0);
  29204. __decorate([
  29205. BABYLON.serializeAsTexture("reflectionTexture")
  29206. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  29207. __decorate([
  29208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29209. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  29210. __decorate([
  29211. BABYLON.serializeAsTexture("emissiveTexture")
  29212. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  29213. __decorate([
  29214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29215. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  29216. __decorate([
  29217. BABYLON.serializeAsTexture("specularTexture")
  29218. ], StandardMaterial.prototype, "_specularTexture", void 0);
  29219. __decorate([
  29220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29221. ], StandardMaterial.prototype, "specularTexture", void 0);
  29222. __decorate([
  29223. BABYLON.serializeAsTexture("bumpTexture")
  29224. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  29225. __decorate([
  29226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29227. ], StandardMaterial.prototype, "bumpTexture", void 0);
  29228. __decorate([
  29229. BABYLON.serializeAsTexture("lightmapTexture")
  29230. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  29231. __decorate([
  29232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29233. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  29234. __decorate([
  29235. BABYLON.serializeAsTexture("refractionTexture")
  29236. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  29237. __decorate([
  29238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29239. ], StandardMaterial.prototype, "refractionTexture", void 0);
  29240. __decorate([
  29241. BABYLON.serializeAsColor3("ambient")
  29242. ], StandardMaterial.prototype, "ambientColor", void 0);
  29243. __decorate([
  29244. BABYLON.serializeAsColor3("diffuse")
  29245. ], StandardMaterial.prototype, "diffuseColor", void 0);
  29246. __decorate([
  29247. BABYLON.serializeAsColor3("specular")
  29248. ], StandardMaterial.prototype, "specularColor", void 0);
  29249. __decorate([
  29250. BABYLON.serializeAsColor3("emissive")
  29251. ], StandardMaterial.prototype, "emissiveColor", void 0);
  29252. __decorate([
  29253. BABYLON.serialize()
  29254. ], StandardMaterial.prototype, "specularPower", void 0);
  29255. __decorate([
  29256. BABYLON.serialize("useAlphaFromDiffuseTexture")
  29257. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  29258. __decorate([
  29259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29260. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  29261. __decorate([
  29262. BABYLON.serialize("useEmissiveAsIllumination")
  29263. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  29264. __decorate([
  29265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29266. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29267. __decorate([
  29268. BABYLON.serialize("linkEmissiveWithDiffuse")
  29269. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  29270. __decorate([
  29271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29272. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  29273. __decorate([
  29274. BABYLON.serialize("useSpecularOverAlpha")
  29275. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  29276. __decorate([
  29277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29278. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  29279. __decorate([
  29280. BABYLON.serialize("useReflectionOverAlpha")
  29281. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  29282. __decorate([
  29283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29284. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  29285. __decorate([
  29286. BABYLON.serialize("disableLighting")
  29287. ], StandardMaterial.prototype, "_disableLighting", void 0);
  29288. __decorate([
  29289. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29290. ], StandardMaterial.prototype, "disableLighting", void 0);
  29291. __decorate([
  29292. BABYLON.serialize("useParallax")
  29293. ], StandardMaterial.prototype, "_useParallax", void 0);
  29294. __decorate([
  29295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29296. ], StandardMaterial.prototype, "useParallax", void 0);
  29297. __decorate([
  29298. BABYLON.serialize("useParallaxOcclusion")
  29299. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  29300. __decorate([
  29301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29302. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  29303. __decorate([
  29304. BABYLON.serialize()
  29305. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  29306. __decorate([
  29307. BABYLON.serialize("roughness")
  29308. ], StandardMaterial.prototype, "_roughness", void 0);
  29309. __decorate([
  29310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29311. ], StandardMaterial.prototype, "roughness", void 0);
  29312. __decorate([
  29313. BABYLON.serialize()
  29314. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  29315. __decorate([
  29316. BABYLON.serialize()
  29317. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  29318. __decorate([
  29319. BABYLON.serialize("useLightmapAsShadowmap")
  29320. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  29321. __decorate([
  29322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29323. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  29324. __decorate([
  29325. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  29326. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  29327. __decorate([
  29328. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29329. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  29330. __decorate([
  29331. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  29332. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  29333. __decorate([
  29334. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29335. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  29336. __decorate([
  29337. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  29338. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  29339. __decorate([
  29340. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29341. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  29342. __decorate([
  29343. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  29344. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  29345. __decorate([
  29346. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29347. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  29348. __decorate([
  29349. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  29350. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  29351. __decorate([
  29352. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29353. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  29354. __decorate([
  29355. BABYLON.serialize("useReflectionFresnelFromSpecular")
  29356. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  29357. __decorate([
  29358. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29359. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  29360. __decorate([
  29361. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  29362. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  29363. __decorate([
  29364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29365. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  29366. __decorate([
  29367. BABYLON.serialize("maxSimultaneousLights")
  29368. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  29369. __decorate([
  29370. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29371. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  29372. __decorate([
  29373. BABYLON.serialize("invertNormalMapX")
  29374. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  29375. __decorate([
  29376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29377. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  29378. __decorate([
  29379. BABYLON.serialize("invertNormalMapY")
  29380. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  29381. __decorate([
  29382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29383. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  29384. __decorate([
  29385. BABYLON.serialize("twoSidedLighting")
  29386. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  29387. __decorate([
  29388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29389. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  29390. __decorate([
  29391. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  29392. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  29393. __decorate([
  29394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29395. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  29396. __decorate([
  29397. BABYLON.serializeAsColorCurves("cameraColorCurves")
  29398. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  29399. __decorate([
  29400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29401. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  29402. __decorate([
  29403. BABYLON.serialize()
  29404. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  29405. BABYLON.StandardMaterial = StandardMaterial;
  29406. })(BABYLON || (BABYLON = {}));
  29407. //# sourceMappingURL=babylon.standardMaterial.js.map
  29408. var BABYLON;
  29409. (function (BABYLON) {
  29410. var PBRMaterialDefines = (function (_super) {
  29411. __extends(PBRMaterialDefines, _super);
  29412. function PBRMaterialDefines() {
  29413. var _this = _super.call(this) || this;
  29414. _this.PBR = true;
  29415. _this.ALBEDO = false;
  29416. _this.AMBIENT = false;
  29417. _this.AMBIENTINGRAYSCALE = false;
  29418. _this.OPACITY = false;
  29419. _this.OPACITYRGB = false;
  29420. _this.REFLECTION = false;
  29421. _this.EMISSIVE = false;
  29422. _this.REFLECTIVITY = false;
  29423. _this.BUMP = false;
  29424. _this.PARALLAX = false;
  29425. _this.PARALLAXOCCLUSION = false;
  29426. _this.SPECULAROVERALPHA = false;
  29427. _this.CLIPPLANE = false;
  29428. _this.ALPHATEST = false;
  29429. _this.ALPHAFROMALBEDO = false;
  29430. _this.POINTSIZE = false;
  29431. _this.FOG = false;
  29432. _this.SPECULARTERM = false;
  29433. _this.OPACITYFRESNEL = false;
  29434. _this.EMISSIVEFRESNEL = false;
  29435. _this.FRESNEL = false;
  29436. _this.NORMAL = false;
  29437. _this.TANGENT = false;
  29438. _this.UV1 = false;
  29439. _this.UV2 = false;
  29440. _this.VERTEXCOLOR = false;
  29441. _this.VERTEXALPHA = false;
  29442. _this.NUM_BONE_INFLUENCERS = 0;
  29443. _this.BonesPerMesh = 0;
  29444. _this.INSTANCES = false;
  29445. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  29446. _this.MICROSURFACEAUTOMATIC = false;
  29447. _this.EMISSIVEASILLUMINATION = false;
  29448. _this.LIGHTMAP = false;
  29449. _this.USELIGHTMAPASSHADOWMAP = false;
  29450. _this.REFLECTIONMAP_3D = false;
  29451. _this.REFLECTIONMAP_SPHERICAL = false;
  29452. _this.REFLECTIONMAP_PLANAR = false;
  29453. _this.REFLECTIONMAP_CUBIC = false;
  29454. _this.REFLECTIONMAP_PROJECTION = false;
  29455. _this.REFLECTIONMAP_SKYBOX = false;
  29456. _this.REFLECTIONMAP_EXPLICIT = false;
  29457. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29458. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29459. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  29460. _this.INVERTCUBICMAP = false;
  29461. _this.LOGARITHMICDEPTH = false;
  29462. _this.CAMERATONEMAP = false;
  29463. _this.CAMERACONTRAST = false;
  29464. _this.CAMERACOLORGRADING = false;
  29465. _this.CAMERACOLORCURVES = false;
  29466. _this.USESPHERICALFROMREFLECTIONMAP = false;
  29467. _this.REFRACTION = false;
  29468. _this.REFRACTIONMAP_3D = false;
  29469. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  29470. _this.REFRACTIONMAPINLINEARSPACE = false;
  29471. _this.LODBASEDMICROSFURACE = false;
  29472. _this.USEPHYSICALLIGHTFALLOFF = false;
  29473. _this.RADIANCEOVERALPHA = false;
  29474. _this.USEPMREMREFLECTION = false;
  29475. _this.USEPMREMREFRACTION = false;
  29476. _this.INVERTNORMALMAPX = false;
  29477. _this.INVERTNORMALMAPY = false;
  29478. _this.TWOSIDEDLIGHTING = false;
  29479. _this.SHADOWFLOAT = false;
  29480. _this.NORMALXYSCALE = true;
  29481. _this.USERIGHTHANDEDSYSTEM = false;
  29482. _this.METALLICWORKFLOW = false;
  29483. _this.METALLICMAP = false;
  29484. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  29485. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  29486. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  29487. _this.AOSTOREINMETALMAPRED = false;
  29488. _this.MICROSURFACEMAP = false;
  29489. _this.MORPHTARGETS = false;
  29490. _this.MORPHTARGETS_NORMAL = false;
  29491. _this.MORPHTARGETS_TANGENT = false;
  29492. _this.NUM_MORPH_INFLUENCERS = 0;
  29493. _this.ALPHATESTVALUE = 0.4;
  29494. _this.LDROUTPUT = true;
  29495. _this.rebuild();
  29496. return _this;
  29497. }
  29498. PBRMaterialDefines.prototype.reset = function () {
  29499. _super.prototype.reset.call(this);
  29500. this.ALPHATESTVALUE = 0.4;
  29501. this.PBR = true;
  29502. };
  29503. return PBRMaterialDefines;
  29504. }(BABYLON.MaterialDefines));
  29505. /**
  29506. * The Physically based material base class of BJS.
  29507. *
  29508. * This offers the main features of a standard PBR material.
  29509. * For more information, please refer to the documentation :
  29510. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  29511. */
  29512. var PBRBaseMaterial = (function (_super) {
  29513. __extends(PBRBaseMaterial, _super);
  29514. /**
  29515. * Instantiates a new PBRMaterial instance.
  29516. *
  29517. * @param name The material name
  29518. * @param scene The scene the material will be use in.
  29519. */
  29520. function PBRBaseMaterial(name, scene) {
  29521. var _this = _super.call(this, name, scene) || this;
  29522. /**
  29523. * Intensity of the direct lights e.g. the four lights available in your scene.
  29524. * This impacts both the direct diffuse and specular highlights.
  29525. */
  29526. _this._directIntensity = 1.0;
  29527. /**
  29528. * Intensity of the emissive part of the material.
  29529. * This helps controlling the emissive effect without modifying the emissive color.
  29530. */
  29531. _this._emissiveIntensity = 1.0;
  29532. /**
  29533. * Intensity of the environment e.g. how much the environment will light the object
  29534. * either through harmonics for rough material or through the refelction for shiny ones.
  29535. */
  29536. _this._environmentIntensity = 1.0;
  29537. /**
  29538. * This is a special control allowing the reduction of the specular highlights coming from the
  29539. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  29540. */
  29541. _this._specularIntensity = 1.0;
  29542. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  29543. /**
  29544. * Debug Control allowing disabling the bump map on this material.
  29545. */
  29546. _this._disableBumpMap = false;
  29547. /**
  29548. * The camera exposure used on this material.
  29549. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  29550. * This corresponds to a photographic exposure.
  29551. */
  29552. _this._cameraExposure = 1.0;
  29553. /**
  29554. * The camera contrast used on this material.
  29555. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  29556. */
  29557. _this._cameraContrast = 1.0;
  29558. /**
  29559. * Color Grading 2D Lookup Texture.
  29560. * This allows special effects like sepia, black and white to sixties rendering style.
  29561. */
  29562. _this._cameraColorGradingTexture = null;
  29563. /**
  29564. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  29565. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  29566. * 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;
  29567. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  29568. */
  29569. _this._cameraColorCurves = null;
  29570. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  29571. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  29572. /**
  29573. * AKA Occlusion Texture Intensity in other nomenclature.
  29574. */
  29575. _this._ambientTextureStrength = 1.0;
  29576. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  29577. /**
  29578. * AKA Diffuse Color in other nomenclature.
  29579. */
  29580. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  29581. /**
  29582. * AKA Specular Color in other nomenclature.
  29583. */
  29584. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  29585. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  29586. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  29587. /**
  29588. * AKA Glossiness in other nomenclature.
  29589. */
  29590. _this._microSurface = 0.9;
  29591. /**
  29592. * source material index of refraction (IOR)' / 'destination material IOR.
  29593. */
  29594. _this._indexOfRefraction = 0.66;
  29595. /**
  29596. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  29597. */
  29598. _this._invertRefractionY = false;
  29599. /**
  29600. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  29601. * Materials half opaque for instance using refraction could benefit from this control.
  29602. */
  29603. _this._linkRefractionWithTransparency = false;
  29604. _this._useLightmapAsShadowmap = false;
  29605. /**
  29606. * In this mode, the emissive informtaion will always be added to the lighting once.
  29607. * A light for instance can be thought as emissive.
  29608. */
  29609. _this._useEmissiveAsIllumination = false;
  29610. /**
  29611. * Secifies that the alpha is coming form the albedo channel alpha channel.
  29612. */
  29613. _this._useAlphaFromAlbedoTexture = false;
  29614. /**
  29615. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  29616. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  29617. */
  29618. _this._useSpecularOverAlpha = true;
  29619. /**
  29620. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  29621. */
  29622. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  29623. /**
  29624. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  29625. */
  29626. _this._useRoughnessFromMetallicTextureAlpha = true;
  29627. /**
  29628. * Specifies if the metallic texture contains the roughness information in its green channel.
  29629. */
  29630. _this._useRoughnessFromMetallicTextureGreen = false;
  29631. /**
  29632. * Specifies if the metallic texture contains the metallness information in its blue channel.
  29633. */
  29634. _this._useMetallnessFromMetallicTextureBlue = false;
  29635. /**
  29636. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  29637. */
  29638. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  29639. /**
  29640. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  29641. */
  29642. _this._useAmbientInGrayScale = false;
  29643. /**
  29644. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  29645. * The material will try to infer what glossiness each pixel should be.
  29646. */
  29647. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  29648. /**
  29649. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  29650. * the creation of the material.
  29651. */
  29652. _this._useScalarInLinearSpace = false;
  29653. /**
  29654. * BJS is using an harcoded light falloff based on a manually sets up range.
  29655. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  29656. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  29657. */
  29658. _this._usePhysicalLightFalloff = true;
  29659. /**
  29660. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  29661. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  29662. */
  29663. _this._useRadianceOverAlpha = true;
  29664. /**
  29665. * Allows using the bump map in parallax mode.
  29666. */
  29667. _this._useParallax = false;
  29668. /**
  29669. * Allows using the bump map in parallax occlusion mode.
  29670. */
  29671. _this._useParallaxOcclusion = false;
  29672. /**
  29673. * Controls the scale bias of the parallax mode.
  29674. */
  29675. _this._parallaxScaleBias = 0.05;
  29676. /**
  29677. * If sets to true, disables all the lights affecting the material.
  29678. */
  29679. _this._disableLighting = false;
  29680. /**
  29681. * Number of Simultaneous lights allowed on the material.
  29682. */
  29683. _this._maxSimultaneousLights = 4;
  29684. /**
  29685. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29686. */
  29687. _this._invertNormalMapX = false;
  29688. /**
  29689. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  29690. */
  29691. _this._invertNormalMapY = false;
  29692. /**
  29693. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  29694. */
  29695. _this._twoSidedLighting = false;
  29696. /**
  29697. * Defines the alpha limits in alpha test mode.
  29698. */
  29699. _this._alphaCutOff = 0.4;
  29700. /**
  29701. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  29702. */
  29703. _this._forceAlphaTest = false;
  29704. /**
  29705. * If false, it allows the output of the shader to be in hdr space (e.g. more than one) which is usefull
  29706. * in combination of post process in float or half float mode.
  29707. */
  29708. _this._ldrOutput = true;
  29709. _this._renderTargets = new BABYLON.SmartArray(16);
  29710. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  29711. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  29712. _this._tempColor = new BABYLON.Color3();
  29713. _this._defines = new PBRMaterialDefines();
  29714. _this._cachedDefines = new PBRMaterialDefines();
  29715. _this._myScene = null;
  29716. _this._myShadowGenerator = null;
  29717. _this._cachedDefines.BonesPerMesh = -1;
  29718. _this.getRenderTargetTextures = function () {
  29719. _this._renderTargets.reset();
  29720. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  29721. _this._renderTargets.push(_this._reflectionTexture);
  29722. }
  29723. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  29724. _this._renderTargets.push(_this._refractionTexture);
  29725. }
  29726. return _this._renderTargets;
  29727. };
  29728. return _this;
  29729. }
  29730. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  29731. get: function () {
  29732. return this._useLogarithmicDepth;
  29733. },
  29734. set: function (value) {
  29735. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  29736. },
  29737. enumerable: true,
  29738. configurable: true
  29739. });
  29740. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  29741. if (this._linkRefractionWithTransparency) {
  29742. return false;
  29743. }
  29744. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  29745. };
  29746. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  29747. if (this._linkRefractionWithTransparency) {
  29748. return false;
  29749. }
  29750. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  29751. };
  29752. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  29753. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  29754. };
  29755. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  29756. return this._albedoTexture;
  29757. };
  29758. PBRBaseMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  29759. if (!mesh) {
  29760. return true;
  29761. }
  29762. if (this._defines.INSTANCES !== useInstances) {
  29763. return false;
  29764. }
  29765. return false;
  29766. };
  29767. PBRBaseMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  29768. BABYLON.PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this._useScalarInLinearSpace);
  29769. };
  29770. PBRBaseMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  29771. if (!useScalarInLinear) {
  29772. color.toLinearSpaceToRef(ref);
  29773. }
  29774. else {
  29775. ref.r = color.r;
  29776. ref.g = color.g;
  29777. ref.b = color.b;
  29778. }
  29779. };
  29780. PBRBaseMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  29781. var lightIndex = 0;
  29782. var depthValuesAlreadySet = false;
  29783. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  29784. var light = _a[_i];
  29785. var useUbo = light._uniformBuffer.useUbo;
  29786. var scaledIntensity = light.getScaledIntensity();
  29787. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  29788. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  29789. // GAMMA CORRECTION.
  29790. this.convertColorToLinearSpaceToRef(light.diffuse, BABYLON.PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  29791. BABYLON.PBRMaterial._scaledAlbedo.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledAlbedo);
  29792. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, BABYLON.PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  29793. if (defines["SPECULARTERM"]) {
  29794. this.convertColorToLinearSpaceToRef(light.specular, BABYLON.PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  29795. BABYLON.PBRMaterial._scaledReflectivity.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledReflectivity);
  29796. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, BABYLON.PBRMaterial._scaledReflectivity);
  29797. }
  29798. // Shadows
  29799. if (scene.shadowsEnabled) {
  29800. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  29801. }
  29802. light._uniformBuffer.update();
  29803. lightIndex++;
  29804. if (lightIndex === maxSimultaneousLights)
  29805. break;
  29806. }
  29807. };
  29808. PBRBaseMaterial.prototype.isReady = function (mesh, useInstances) {
  29809. if (this.isFrozen) {
  29810. if (this._wasPreviouslyReady) {
  29811. return true;
  29812. }
  29813. }
  29814. var scene = this.getScene();
  29815. var engine = scene.getEngine();
  29816. var needUVs = false;
  29817. this._defines.reset();
  29818. if (scene.lightsEnabled && !this._disableLighting) {
  29819. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this._maxSimultaneousLights);
  29820. }
  29821. if (!this.checkReadyOnEveryCall) {
  29822. if (this._renderId === scene.getRenderId()) {
  29823. if (this._checkCache(scene, mesh, useInstances)) {
  29824. return true;
  29825. }
  29826. }
  29827. }
  29828. if (scene.texturesEnabled) {
  29829. if (scene.getEngine().getCaps().textureLOD) {
  29830. this._defines.LODBASEDMICROSFURACE = true;
  29831. }
  29832. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29833. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  29834. return false;
  29835. }
  29836. needUVs = true;
  29837. this._defines.ALBEDO = true;
  29838. }
  29839. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29840. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  29841. return false;
  29842. }
  29843. needUVs = true;
  29844. this._defines.AMBIENT = true;
  29845. this._defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  29846. }
  29847. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29848. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  29849. return false;
  29850. }
  29851. needUVs = true;
  29852. this._defines.OPACITY = true;
  29853. if (this._opacityTexture.getAlphaFromRGB) {
  29854. this._defines.OPACITYRGB = true;
  29855. }
  29856. }
  29857. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  29858. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29859. if (!reflectionTexture.isReadyOrNotBlocking()) {
  29860. return false;
  29861. }
  29862. this._defines.REFLECTION = true;
  29863. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  29864. this._defines.INVERTCUBICMAP = true;
  29865. }
  29866. this._defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  29867. switch (reflectionTexture.coordinatesMode) {
  29868. case BABYLON.Texture.CUBIC_MODE:
  29869. case BABYLON.Texture.INVCUBIC_MODE:
  29870. this._defines.REFLECTIONMAP_CUBIC = true;
  29871. break;
  29872. case BABYLON.Texture.EXPLICIT_MODE:
  29873. this._defines.REFLECTIONMAP_EXPLICIT = true;
  29874. break;
  29875. case BABYLON.Texture.PLANAR_MODE:
  29876. this._defines.REFLECTIONMAP_PLANAR = true;
  29877. break;
  29878. case BABYLON.Texture.PROJECTION_MODE:
  29879. this._defines.REFLECTIONMAP_PROJECTION = true;
  29880. break;
  29881. case BABYLON.Texture.SKYBOX_MODE:
  29882. this._defines.REFLECTIONMAP_SKYBOX = true;
  29883. break;
  29884. case BABYLON.Texture.SPHERICAL_MODE:
  29885. this._defines.REFLECTIONMAP_SPHERICAL = true;
  29886. break;
  29887. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  29888. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  29889. break;
  29890. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  29891. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  29892. break;
  29893. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  29894. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  29895. break;
  29896. }
  29897. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  29898. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  29899. if (reflectionTexture.isPMREM) {
  29900. this._defines.USEPMREMREFLECTION = true;
  29901. }
  29902. }
  29903. }
  29904. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29905. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  29906. return false;
  29907. }
  29908. needUVs = true;
  29909. this._defines.LIGHTMAP = true;
  29910. this._defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  29911. }
  29912. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29913. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  29914. return false;
  29915. }
  29916. needUVs = true;
  29917. this._defines.EMISSIVE = true;
  29918. }
  29919. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29920. if (this._metallicTexture) {
  29921. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  29922. return false;
  29923. }
  29924. needUVs = true;
  29925. this._defines.METALLICWORKFLOW = true;
  29926. this._defines.METALLICMAP = true;
  29927. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  29928. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  29929. this._defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  29930. this._defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  29931. }
  29932. else if (this._reflectivityTexture) {
  29933. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  29934. return false;
  29935. }
  29936. needUVs = true;
  29937. this._defines.REFLECTIVITY = true;
  29938. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  29939. this._defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  29940. }
  29941. if (this._microSurfaceTexture) {
  29942. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  29943. return false;
  29944. }
  29945. needUVs = true;
  29946. this._defines.MICROSURFACEMAP = true;
  29947. }
  29948. }
  29949. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  29950. // Bump texure can not be none blocking.
  29951. if (!this._bumpTexture.isReady()) {
  29952. return false;
  29953. }
  29954. needUVs = true;
  29955. this._defines.BUMP = true;
  29956. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29957. this._defines.PARALLAX = true;
  29958. if (this._useParallaxOcclusion) {
  29959. this._defines.PARALLAXOCCLUSION = true;
  29960. }
  29961. }
  29962. if (this._invertNormalMapX) {
  29963. this._defines.INVERTNORMALMAPX = true;
  29964. }
  29965. if (this._invertNormalMapY) {
  29966. this._defines.INVERTNORMALMAPY = true;
  29967. }
  29968. if (scene._mirroredCameraPosition) {
  29969. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  29970. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  29971. }
  29972. this._defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  29973. }
  29974. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29975. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  29976. return false;
  29977. }
  29978. needUVs = true;
  29979. this._defines.REFRACTION = true;
  29980. this._defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  29981. if (this._linkRefractionWithTransparency) {
  29982. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  29983. }
  29984. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  29985. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  29986. if (this._refractionTexture.isPMREM) {
  29987. this._defines.USEPMREMREFRACTION = true;
  29988. }
  29989. }
  29990. }
  29991. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  29992. // Color Grading texure can not be none blocking.
  29993. if (!this._cameraColorGradingTexture.isReady()) {
  29994. return false;
  29995. }
  29996. this._defines.CAMERACOLORGRADING = true;
  29997. }
  29998. if (!this.backFaceCulling && this._twoSidedLighting) {
  29999. this._defines.TWOSIDEDLIGHTING = true;
  30000. }
  30001. }
  30002. this._defines.LDROUTPUT = this._ldrOutput;
  30003. // Effect
  30004. if (scene.clipPlane) {
  30005. this._defines.CLIPPLANE = true;
  30006. }
  30007. this._defines.ALPHATESTVALUE = this._alphaCutOff;
  30008. if (engine.getAlphaTesting() || this._forceAlphaTest) {
  30009. this._defines.ALPHATEST = true;
  30010. }
  30011. if (this._shouldUseAlphaFromAlbedoTexture()) {
  30012. this._defines.ALPHAFROMALBEDO = true;
  30013. }
  30014. if (this._useEmissiveAsIllumination) {
  30015. this._defines.EMISSIVEASILLUMINATION = true;
  30016. }
  30017. if (this.useLogarithmicDepth) {
  30018. this._defines.LOGARITHMICDEPTH = true;
  30019. }
  30020. if (this._cameraContrast != 1) {
  30021. this._defines.CAMERACONTRAST = true;
  30022. }
  30023. if (this._cameraExposure != 1) {
  30024. this._defines.CAMERATONEMAP = true;
  30025. }
  30026. if (this._cameraColorCurves) {
  30027. this._defines.CAMERACOLORCURVES = true;
  30028. }
  30029. // Point size
  30030. if (this.pointsCloud || scene.forcePointsCloud) {
  30031. this._defines.POINTSIZE = true;
  30032. }
  30033. // Fog
  30034. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  30035. this._defines.FOG = true;
  30036. }
  30037. if (BABYLON.StandardMaterial.FresnelEnabled) {
  30038. // Fresnel
  30039. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  30040. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  30041. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  30042. this._defines.OPACITYFRESNEL = true;
  30043. }
  30044. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  30045. this._defines.EMISSIVEFRESNEL = true;
  30046. }
  30047. this._defines.FRESNEL = true;
  30048. }
  30049. }
  30050. if (this._defines.SPECULARTERM && this._useSpecularOverAlpha) {
  30051. this._defines.SPECULAROVERALPHA = true;
  30052. }
  30053. if (this._usePhysicalLightFalloff) {
  30054. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  30055. }
  30056. if (this._useRadianceOverAlpha) {
  30057. this._defines.RADIANCEOVERALPHA = true;
  30058. }
  30059. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  30060. this._defines.METALLICWORKFLOW = true;
  30061. }
  30062. // Attribs
  30063. if (mesh) {
  30064. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30065. mesh.createNormals(true);
  30066. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  30067. }
  30068. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30069. this._defines.NORMAL = true;
  30070. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30071. this._defines.TANGENT = true;
  30072. }
  30073. }
  30074. if (needUVs) {
  30075. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30076. this._defines.UV1 = true;
  30077. }
  30078. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30079. this._defines.UV2 = true;
  30080. }
  30081. }
  30082. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30083. this._defines.VERTEXCOLOR = true;
  30084. if (mesh.hasVertexAlpha) {
  30085. this._defines.VERTEXALPHA = true;
  30086. }
  30087. }
  30088. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30089. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  30090. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  30091. }
  30092. // Instances
  30093. if (useInstances) {
  30094. this._defines.INSTANCES = true;
  30095. }
  30096. if (mesh.morphTargetManager) {
  30097. var manager = mesh.morphTargetManager;
  30098. this._defines.MORPHTARGETS_TANGENT = manager.supportsTangents && this._defines.TANGENT;
  30099. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  30100. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  30101. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  30102. }
  30103. }
  30104. // Get correct effect
  30105. if (!this._defines.isEqual(this._cachedDefines)) {
  30106. this._defines.cloneTo(this._cachedDefines);
  30107. scene.resetCachedMaterial();
  30108. // Fallbacks
  30109. var fallbacks = new BABYLON.EffectFallbacks();
  30110. if (this._defines.REFLECTION) {
  30111. fallbacks.addFallback(0, "REFLECTION");
  30112. }
  30113. if (this._defines.REFRACTION) {
  30114. fallbacks.addFallback(0, "REFRACTION");
  30115. }
  30116. if (this._defines.REFLECTIVITY) {
  30117. fallbacks.addFallback(0, "REFLECTIVITY");
  30118. }
  30119. if (this._defines.BUMP) {
  30120. fallbacks.addFallback(0, "BUMP");
  30121. }
  30122. if (this._defines.PARALLAX) {
  30123. fallbacks.addFallback(1, "PARALLAX");
  30124. }
  30125. if (this._defines.PARALLAXOCCLUSION) {
  30126. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30127. }
  30128. if (this._defines.SPECULAROVERALPHA) {
  30129. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30130. }
  30131. if (this._defines.FOG) {
  30132. fallbacks.addFallback(1, "FOG");
  30133. }
  30134. if (this._defines.POINTSIZE) {
  30135. fallbacks.addFallback(0, "POINTSIZE");
  30136. }
  30137. if (this._defines.LOGARITHMICDEPTH) {
  30138. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30139. }
  30140. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this._maxSimultaneousLights);
  30141. if (this._defines.SPECULARTERM) {
  30142. fallbacks.addFallback(0, "SPECULARTERM");
  30143. }
  30144. if (this._defines.OPACITYFRESNEL) {
  30145. fallbacks.addFallback(1, "OPACITYFRESNEL");
  30146. }
  30147. if (this._defines.EMISSIVEFRESNEL) {
  30148. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  30149. }
  30150. if (this._defines.FRESNEL) {
  30151. fallbacks.addFallback(3, "FRESNEL");
  30152. }
  30153. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  30154. fallbacks.addCPUSkinningFallback(0, mesh);
  30155. }
  30156. //Attributes
  30157. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30158. if (this._defines.NORMAL) {
  30159. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30160. }
  30161. if (this._defines.TANGENT) {
  30162. attribs.push(BABYLON.VertexBuffer.TangentKind);
  30163. }
  30164. if (this._defines.UV1) {
  30165. attribs.push(BABYLON.VertexBuffer.UVKind);
  30166. }
  30167. if (this._defines.UV2) {
  30168. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30169. }
  30170. if (this._defines.VERTEXCOLOR) {
  30171. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30172. }
  30173. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  30174. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  30175. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  30176. // Legacy browser patch
  30177. var join = this._defines.toString();
  30178. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  30179. "vFogInfos", "vFogColor", "pointSize",
  30180. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30181. "mBones",
  30182. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30183. "depthValues",
  30184. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  30185. "vLightingIntensity",
  30186. "logarithmicDepthConstant",
  30187. "vSphericalX", "vSphericalY", "vSphericalZ",
  30188. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  30189. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  30190. "vMicrosurfaceTextureLods",
  30191. "vCameraInfos"
  30192. ];
  30193. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30194. var uniformBuffers = ["Material", "Scene"];
  30195. if (this._defines.CAMERACOLORCURVES) {
  30196. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  30197. }
  30198. if (this._defines.CAMERACOLORGRADING) {
  30199. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  30200. }
  30201. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30202. uniformsNames: uniforms,
  30203. uniformBuffersNames: uniformBuffers,
  30204. samplers: samplers,
  30205. defines: this._defines,
  30206. maxSimultaneousLights: this._maxSimultaneousLights
  30207. });
  30208. var onCompiled = function (effect) {
  30209. if (this.onCompiled) {
  30210. this.onCompiled(effect);
  30211. }
  30212. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  30213. }.bind(this);
  30214. this._effect = scene.getEngine().createEffect("pbr", {
  30215. attributes: attribs,
  30216. uniformsNames: uniforms,
  30217. uniformBuffersNames: uniformBuffers,
  30218. samplers: samplers,
  30219. defines: join,
  30220. fallbacks: fallbacks,
  30221. onCompiled: onCompiled,
  30222. onError: this.onError,
  30223. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS }
  30224. }, engine);
  30225. this.buildUniformLayout();
  30226. }
  30227. if (!this._effect.isReady()) {
  30228. return false;
  30229. }
  30230. this._renderId = scene.getRenderId();
  30231. this._wasPreviouslyReady = true;
  30232. return true;
  30233. };
  30234. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  30235. // Order is important !
  30236. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  30237. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  30238. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  30239. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  30240. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  30241. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  30242. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  30243. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  30244. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  30245. this._uniformBuffer.addUniform("vBumpInfos", 3);
  30246. this._uniformBuffer.addUniform("albedoMatrix", 16);
  30247. this._uniformBuffer.addUniform("ambientMatrix", 16);
  30248. this._uniformBuffer.addUniform("opacityMatrix", 16);
  30249. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  30250. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  30251. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  30252. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  30253. this._uniformBuffer.addUniform("bumpMatrix", 16);
  30254. this._uniformBuffer.addUniform("refractionMatrix", 16);
  30255. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  30256. this._uniformBuffer.addUniform("vReflectionColor", 3);
  30257. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  30258. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  30259. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  30260. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  30261. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  30262. this._uniformBuffer.addUniform("opacityParts", 4);
  30263. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  30264. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  30265. this._uniformBuffer.addUniform("pointSize", 1);
  30266. this._uniformBuffer.create();
  30267. };
  30268. PBRBaseMaterial.prototype.unbind = function () {
  30269. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  30270. this._uniformBuffer.setTexture("reflection2DSampler", null);
  30271. }
  30272. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  30273. this._uniformBuffer.setTexture("refraction2DSampler", null);
  30274. }
  30275. _super.prototype.unbind.call(this);
  30276. };
  30277. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30278. this._effect.setMatrix("world", world);
  30279. };
  30280. PBRBaseMaterial.prototype.bind = function (world, mesh) {
  30281. this._myScene = this.getScene();
  30282. var effect = this._effect;
  30283. // Matrices
  30284. this.bindOnlyWorldMatrix(world);
  30285. // Bones
  30286. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  30287. if (this._myScene.getCachedMaterial() !== this) {
  30288. this._uniformBuffer.bindToEffect(effect, "Material");
  30289. this.bindViewProjection(effect);
  30290. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  30291. // Fresnel
  30292. if (BABYLON.StandardMaterial.FresnelEnabled) {
  30293. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  30294. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this._opacityFresnelParameters.leftColor.toLuminance(), this._opacityFresnelParameters.rightColor.toLuminance(), this._opacityFresnelParameters.bias), this._opacityFresnelParameters.power);
  30295. }
  30296. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  30297. this._uniformBuffer.updateColor4("emissiveLeftColor", this._emissiveFresnelParameters.leftColor, this._emissiveFresnelParameters.power);
  30298. this._uniformBuffer.updateColor4("emissiveRightColor", this._emissiveFresnelParameters.rightColor, this._emissiveFresnelParameters.bias);
  30299. }
  30300. }
  30301. // Texture uniforms
  30302. if (this._myScene.texturesEnabled) {
  30303. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30304. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  30305. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  30306. }
  30307. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30308. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  30309. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  30310. }
  30311. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30312. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  30313. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  30314. }
  30315. var reflectionTexture = this._reflectionTexture || this._myScene.environmentTexture;
  30316. ;
  30317. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30318. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  30319. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  30320. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  30321. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  30322. this._effect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  30323. this._effect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  30324. this._effect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  30325. this._effect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  30326. this._effect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  30327. this._effect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  30328. this._effect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  30329. this._effect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  30330. this._effect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  30331. }
  30332. }
  30333. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30334. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  30335. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  30336. }
  30337. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30338. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  30339. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  30340. }
  30341. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30342. if (this._metallicTexture) {
  30343. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  30344. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  30345. }
  30346. else if (this._reflectivityTexture) {
  30347. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  30348. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  30349. }
  30350. if (this._microSurfaceTexture) {
  30351. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  30352. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  30353. }
  30354. }
  30355. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30356. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  30357. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  30358. }
  30359. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30360. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  30361. var depth = 1.0;
  30362. if (!this._refractionTexture.isCube) {
  30363. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  30364. if (this._refractionTexture.depth) {
  30365. depth = this._refractionTexture.depth;
  30366. }
  30367. }
  30368. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  30369. }
  30370. if ((reflectionTexture || this._refractionTexture)) {
  30371. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  30372. }
  30373. }
  30374. // Point size
  30375. if (this.pointsCloud) {
  30376. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  30377. }
  30378. // Colors
  30379. if (this._defines.METALLICWORKFLOW) {
  30380. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  30381. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  30382. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  30383. }
  30384. else {
  30385. // GAMMA CORRECTION.
  30386. this.convertColorToLinearSpaceToRef(this._reflectivityColor, BABYLON.PBRMaterial._scaledReflectivity);
  30387. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, this._microSurface);
  30388. }
  30389. // GAMMA CORRECTION.
  30390. this.convertColorToLinearSpaceToRef(this._emissiveColor, BABYLON.PBRMaterial._scaledEmissive);
  30391. this._uniformBuffer.updateColor3("vEmissiveColor", BABYLON.PBRMaterial._scaledEmissive);
  30392. // GAMMA CORRECTION.
  30393. this.convertColorToLinearSpaceToRef(this._reflectionColor, BABYLON.PBRMaterial._scaledReflection);
  30394. this._uniformBuffer.updateColor3("vReflectionColor", BABYLON.PBRMaterial._scaledReflection);
  30395. // GAMMA CORRECTION.
  30396. this.convertColorToLinearSpaceToRef(this._albedoColor, BABYLON.PBRMaterial._scaledAlbedo);
  30397. this._uniformBuffer.updateColor4("vAlbedoColor", BABYLON.PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  30398. // Misc
  30399. this._lightingInfos.x = this._directIntensity;
  30400. this._lightingInfos.y = this._emissiveIntensity;
  30401. this._lightingInfos.z = this._environmentIntensity;
  30402. this._lightingInfos.w = this._specularIntensity;
  30403. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  30404. }
  30405. // Textures
  30406. if (this._myScene.texturesEnabled) {
  30407. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30408. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  30409. }
  30410. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30411. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  30412. }
  30413. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30414. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  30415. }
  30416. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30417. if (reflectionTexture.isCube) {
  30418. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  30419. }
  30420. else {
  30421. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  30422. }
  30423. }
  30424. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30425. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  30426. }
  30427. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30428. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  30429. }
  30430. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30431. if (this._metallicTexture) {
  30432. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  30433. }
  30434. else if (this._reflectivityTexture) {
  30435. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  30436. }
  30437. if (this._microSurfaceTexture) {
  30438. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  30439. }
  30440. }
  30441. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30442. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  30443. }
  30444. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30445. if (this._refractionTexture.isCube) {
  30446. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  30447. }
  30448. else {
  30449. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  30450. }
  30451. }
  30452. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  30453. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, this._effect);
  30454. }
  30455. }
  30456. // Clip plane
  30457. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  30458. // Colors
  30459. this._myScene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  30460. effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  30461. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30462. }
  30463. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  30464. // Lights
  30465. if (this._myScene.lightsEnabled && !this._disableLighting) {
  30466. BABYLON.PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this._useScalarInLinearSpace, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  30467. }
  30468. // View
  30469. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  30470. this.bindView(effect);
  30471. }
  30472. // Fog
  30473. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  30474. // Morph targets
  30475. if (this._defines.NUM_MORPH_INFLUENCERS) {
  30476. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  30477. }
  30478. this._cameraInfos.x = this._cameraExposure;
  30479. this._cameraInfos.y = this._cameraContrast;
  30480. effect.setVector4("vCameraInfos", this._cameraInfos);
  30481. if (this._cameraColorCurves) {
  30482. BABYLON.ColorCurves.Bind(this._cameraColorCurves, this._effect);
  30483. }
  30484. // Log. depth
  30485. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  30486. }
  30487. this._uniformBuffer.update();
  30488. this._afterBind(mesh);
  30489. this._myScene = null;
  30490. };
  30491. PBRBaseMaterial.prototype.getAnimatables = function () {
  30492. var results = [];
  30493. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  30494. results.push(this._albedoTexture);
  30495. }
  30496. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  30497. results.push(this._ambientTexture);
  30498. }
  30499. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  30500. results.push(this._opacityTexture);
  30501. }
  30502. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  30503. results.push(this._reflectionTexture);
  30504. }
  30505. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  30506. results.push(this._emissiveTexture);
  30507. }
  30508. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  30509. results.push(this._metallicTexture);
  30510. }
  30511. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  30512. results.push(this._reflectivityTexture);
  30513. }
  30514. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  30515. results.push(this._bumpTexture);
  30516. }
  30517. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  30518. results.push(this._lightmapTexture);
  30519. }
  30520. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  30521. results.push(this._refractionTexture);
  30522. }
  30523. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  30524. results.push(this._cameraColorGradingTexture);
  30525. }
  30526. return results;
  30527. };
  30528. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30529. if (forceDisposeTextures) {
  30530. if (this._albedoTexture) {
  30531. this._albedoTexture.dispose();
  30532. }
  30533. if (this._ambientTexture) {
  30534. this._ambientTexture.dispose();
  30535. }
  30536. if (this._opacityTexture) {
  30537. this._opacityTexture.dispose();
  30538. }
  30539. if (this._reflectionTexture) {
  30540. this._reflectionTexture.dispose();
  30541. }
  30542. if (this._emissiveTexture) {
  30543. this._emissiveTexture.dispose();
  30544. }
  30545. if (this._metallicTexture) {
  30546. this._metallicTexture.dispose();
  30547. }
  30548. if (this._reflectivityTexture) {
  30549. this._reflectivityTexture.dispose();
  30550. }
  30551. if (this._bumpTexture) {
  30552. this._bumpTexture.dispose();
  30553. }
  30554. if (this._lightmapTexture) {
  30555. this._lightmapTexture.dispose();
  30556. }
  30557. if (this._refractionTexture) {
  30558. this._refractionTexture.dispose();
  30559. }
  30560. if (this._cameraColorGradingTexture) {
  30561. this._cameraColorGradingTexture.dispose();
  30562. }
  30563. }
  30564. this._renderTargets.dispose();
  30565. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30566. };
  30567. return PBRBaseMaterial;
  30568. }(BABYLON.Material));
  30569. PBRBaseMaterial._scaledAlbedo = new BABYLON.Color3();
  30570. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  30571. PBRBaseMaterial._scaledEmissive = new BABYLON.Color3();
  30572. PBRBaseMaterial._scaledReflection = new BABYLON.Color3();
  30573. __decorate([
  30574. BABYLON.serialize()
  30575. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  30576. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  30577. })(BABYLON || (BABYLON = {}));
  30578. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  30579. var BABYLON;
  30580. (function (BABYLON) {
  30581. var Internals;
  30582. (function (Internals) {
  30583. /**
  30584. * The Physically based simple base material of BJS.
  30585. *
  30586. * This enables better naming and convention enforcements on top of the pbrMaterial.
  30587. * It is used as the base class for both the specGloss and metalRough conventions.
  30588. */
  30589. var PBRBaseSimpleMaterial = (function (_super) {
  30590. __extends(PBRBaseSimpleMaterial, _super);
  30591. /**
  30592. * Instantiates a new PBRMaterial instance.
  30593. *
  30594. * @param name The material name
  30595. * @param scene The scene the material will be use in.
  30596. */
  30597. function PBRBaseSimpleMaterial(name, scene) {
  30598. var _this = _super.call(this, name, scene) || this;
  30599. /**
  30600. * Number of Simultaneous lights allowed on the material.
  30601. */
  30602. _this.maxSimultaneousLights = 4;
  30603. /**
  30604. * If sets to true, disables all the lights affecting the material.
  30605. */
  30606. _this.disableLighting = false;
  30607. /**
  30608. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30609. */
  30610. _this.invertNormalMapX = false;
  30611. /**
  30612. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30613. */
  30614. _this.invertNormalMapY = false;
  30615. /**
  30616. * Emissivie color used to self-illuminate the model.
  30617. */
  30618. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30619. /**
  30620. * Occlusion Channel Strenght.
  30621. */
  30622. _this.occlusionStrength = 1.0;
  30623. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30624. _this._useEmissiveAsIllumination = true;
  30625. _this._useAmbientInGrayScale = true;
  30626. _this._useScalarInLinearSpace = true;
  30627. return _this;
  30628. }
  30629. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  30630. /**
  30631. * Gets the current transparency mode.
  30632. */
  30633. get: function () {
  30634. return this._transparencyMode;
  30635. },
  30636. /**
  30637. * Sets the transparency mode of the material.
  30638. */
  30639. set: function (value) {
  30640. this._transparencyMode = value;
  30641. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  30642. this._forceAlphaTest = true;
  30643. }
  30644. else {
  30645. this._forceAlphaTest = false;
  30646. }
  30647. },
  30648. enumerable: true,
  30649. configurable: true
  30650. });
  30651. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  30652. /**
  30653. * Gets the current double sided mode.
  30654. */
  30655. get: function () {
  30656. return this._twoSidedLighting;
  30657. },
  30658. /**
  30659. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30660. */
  30661. set: function (value) {
  30662. this._twoSidedLighting = value;
  30663. this.backFaceCulling = !value;
  30664. },
  30665. enumerable: true,
  30666. configurable: true
  30667. });
  30668. /**
  30669. * Specifies wether or not the alpha value of the albedo texture should be used.
  30670. */
  30671. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  30672. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30673. };
  30674. /**
  30675. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  30676. */
  30677. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  30678. if (this._linkRefractionWithTransparency) {
  30679. return false;
  30680. }
  30681. return (this.alpha < 1.0) ||
  30682. (this._shouldUseAlphaFromAlbedoTexture() &&
  30683. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  30684. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  30685. };
  30686. /**
  30687. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  30688. */
  30689. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  30690. if (this._linkRefractionWithTransparency) {
  30691. return false;
  30692. }
  30693. return this._shouldUseAlphaFromAlbedoTexture() &&
  30694. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  30695. };
  30696. return PBRBaseSimpleMaterial;
  30697. }(BABYLON.PBRBaseMaterial));
  30698. __decorate([
  30699. BABYLON.serialize(),
  30700. BABYLON.expandToProperty(null)
  30701. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  30702. __decorate([
  30703. BABYLON.serialize(),
  30704. BABYLON.expandToProperty(null)
  30705. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  30706. __decorate([
  30707. BABYLON.serializeAsTexture(),
  30708. BABYLON.expandToProperty(null, "_reflectionTexture")
  30709. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  30710. __decorate([
  30711. BABYLON.serialize(),
  30712. BABYLON.expandToProperty(null)
  30713. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  30714. __decorate([
  30715. BABYLON.serialize(),
  30716. BABYLON.expandToProperty(null)
  30717. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  30718. __decorate([
  30719. BABYLON.serializeAsTexture(),
  30720. BABYLON.expandToProperty(null, "_bumpTexture")
  30721. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  30722. __decorate([
  30723. BABYLON.serializeAsColor3("emissive"),
  30724. BABYLON.expandToProperty(null)
  30725. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  30726. __decorate([
  30727. BABYLON.serializeAsTexture(),
  30728. BABYLON.expandToProperty(null)
  30729. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  30730. __decorate([
  30731. BABYLON.serialize(),
  30732. BABYLON.expandToProperty(null, "_ambientTextureStrength")
  30733. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  30734. __decorate([
  30735. BABYLON.serializeAsTexture(),
  30736. BABYLON.expandToProperty(null, "_ambientTexture")
  30737. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  30738. __decorate([
  30739. BABYLON.serialize(),
  30740. BABYLON.expandToProperty(null, "_alphaCutOff")
  30741. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  30742. __decorate([
  30743. BABYLON.serialize()
  30744. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  30745. __decorate([
  30746. BABYLON.serialize()
  30747. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  30748. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  30749. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30750. })(BABYLON || (BABYLON = {}));
  30751. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  30752. var BABYLON;
  30753. (function (BABYLON) {
  30754. /**
  30755. * The Physically based material of BJS.
  30756. *
  30757. * This offers the main features of a standard PBR material.
  30758. * For more information, please refer to the documentation :
  30759. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  30760. */
  30761. var PBRMaterial = (function (_super) {
  30762. __extends(PBRMaterial, _super);
  30763. /**
  30764. * Instantiates a new PBRMaterial instance.
  30765. *
  30766. * @param name The material name
  30767. * @param scene The scene the material will be use in.
  30768. */
  30769. function PBRMaterial(name, scene) {
  30770. var _this = _super.call(this, name, scene) || this;
  30771. /**
  30772. * Intensity of the direct lights e.g. the four lights available in your scene.
  30773. * This impacts both the direct diffuse and specular highlights.
  30774. */
  30775. _this.directIntensity = 1.0;
  30776. /**
  30777. * Intensity of the emissive part of the material.
  30778. * This helps controlling the emissive effect without modifying the emissive color.
  30779. */
  30780. _this.emissiveIntensity = 1.0;
  30781. /**
  30782. * Intensity of the environment e.g. how much the environment will light the object
  30783. * either through harmonics for rough material or through the refelction for shiny ones.
  30784. */
  30785. _this.environmentIntensity = 1.0;
  30786. /**
  30787. * This is a special control allowing the reduction of the specular highlights coming from the
  30788. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  30789. */
  30790. _this.specularIntensity = 1.0;
  30791. /**
  30792. * Debug Control allowing disabling the bump map on this material.
  30793. */
  30794. _this.disableBumpMap = false;
  30795. /**
  30796. * The camera exposure used on this material.
  30797. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30798. * This corresponds to a photographic exposure.
  30799. */
  30800. _this.cameraExposure = 1.0;
  30801. /**
  30802. * The camera contrast used on this material.
  30803. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  30804. */
  30805. _this.cameraContrast = 1.0;
  30806. /**
  30807. * Color Grading 2D Lookup Texture.
  30808. * This allows special effects like sepia, black and white to sixties rendering style.
  30809. */
  30810. _this.cameraColorGradingTexture = null;
  30811. /**
  30812. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30813. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30814. * 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;
  30815. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30816. */
  30817. _this.cameraColorCurves = null;
  30818. /**
  30819. * AKA Occlusion Texture Intensity in other nomenclature.
  30820. */
  30821. _this.ambientTextureStrength = 1.0;
  30822. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30823. /**
  30824. * AKA Diffuse Color in other nomenclature.
  30825. */
  30826. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  30827. /**
  30828. * AKA Specular Color in other nomenclature.
  30829. */
  30830. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  30831. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  30832. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30833. /**
  30834. * AKA Glossiness in other nomenclature.
  30835. */
  30836. _this.microSurface = 0.9;
  30837. /**
  30838. * source material index of refraction (IOR)' / 'destination material IOR.
  30839. */
  30840. _this.indexOfRefraction = 0.66;
  30841. /**
  30842. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  30843. */
  30844. _this.invertRefractionY = false;
  30845. /**
  30846. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  30847. * Materials half opaque for instance using refraction could benefit from this control.
  30848. */
  30849. _this.linkRefractionWithTransparency = false;
  30850. _this.useLightmapAsShadowmap = false;
  30851. /**
  30852. * In this mode, the emissive informtaion will always be added to the lighting once.
  30853. * A light for instance can be thought as emissive.
  30854. */
  30855. _this.useEmissiveAsIllumination = false;
  30856. /**
  30857. * Secifies that the alpha is coming form the albedo channel alpha channel.
  30858. */
  30859. _this.useAlphaFromAlbedoTexture = false;
  30860. /**
  30861. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  30862. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  30863. */
  30864. _this.useSpecularOverAlpha = true;
  30865. /**
  30866. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  30867. */
  30868. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  30869. /**
  30870. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  30871. */
  30872. _this.useRoughnessFromMetallicTextureAlpha = true;
  30873. /**
  30874. * Specifies if the metallic texture contains the roughness information in its green channel.
  30875. */
  30876. _this.useRoughnessFromMetallicTextureGreen = false;
  30877. /**
  30878. * Specifies if the metallic texture contains the metallness information in its blue channel.
  30879. */
  30880. _this.useMetallnessFromMetallicTextureBlue = false;
  30881. /**
  30882. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  30883. */
  30884. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  30885. /**
  30886. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  30887. */
  30888. _this.useAmbientInGrayScale = false;
  30889. /**
  30890. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  30891. * The material will try to infer what glossiness each pixel should be.
  30892. */
  30893. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  30894. /**
  30895. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  30896. * the creation of the material.
  30897. */
  30898. _this.useScalarInLinearSpace = false;
  30899. /**
  30900. * BJS is using an harcoded light falloff based on a manually sets up range.
  30901. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  30902. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  30903. */
  30904. _this.usePhysicalLightFalloff = true;
  30905. /**
  30906. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  30907. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  30908. */
  30909. _this.useRadianceOverAlpha = true;
  30910. /**
  30911. * Allows using the bump map in parallax mode.
  30912. */
  30913. _this.useParallax = false;
  30914. /**
  30915. * Allows using the bump map in parallax occlusion mode.
  30916. */
  30917. _this.useParallaxOcclusion = false;
  30918. /**
  30919. * Controls the scale bias of the parallax mode.
  30920. */
  30921. _this.parallaxScaleBias = 0.05;
  30922. /**
  30923. * If sets to true, disables all the lights affecting the material.
  30924. */
  30925. _this.disableLighting = false;
  30926. /**
  30927. * Number of Simultaneous lights allowed on the material.
  30928. */
  30929. _this.maxSimultaneousLights = 4;
  30930. /**
  30931. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30932. */
  30933. _this.invertNormalMapX = false;
  30934. /**
  30935. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30936. */
  30937. _this.invertNormalMapY = false;
  30938. /**
  30939. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30940. */
  30941. _this.twoSidedLighting = false;
  30942. return _this;
  30943. }
  30944. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  30945. /**
  30946. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  30947. */
  30948. get: function () {
  30949. return this._PBRMATERIAL_OPAQUE;
  30950. },
  30951. enumerable: true,
  30952. configurable: true
  30953. });
  30954. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  30955. /**
  30956. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  30957. */
  30958. get: function () {
  30959. return this._PBRMATERIAL_ALPHATEST;
  30960. },
  30961. enumerable: true,
  30962. configurable: true
  30963. });
  30964. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  30965. /**
  30966. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  30967. */
  30968. get: function () {
  30969. return this._PBRMATERIAL_ALPHABLEND;
  30970. },
  30971. enumerable: true,
  30972. configurable: true
  30973. });
  30974. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  30975. /**
  30976. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  30977. * They are also discarded below the alpha cutoff threshold to improve performances.
  30978. */
  30979. get: function () {
  30980. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  30981. },
  30982. enumerable: true,
  30983. configurable: true
  30984. });
  30985. PBRMaterial.prototype.getClassName = function () {
  30986. return "PBRMaterial";
  30987. };
  30988. PBRMaterial.prototype.clone = function (name) {
  30989. var _this = this;
  30990. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  30991. };
  30992. PBRMaterial.prototype.serialize = function () {
  30993. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30994. serializationObject.customType = "BABYLON.PBRMaterial";
  30995. return serializationObject;
  30996. };
  30997. // Statics
  30998. PBRMaterial.Parse = function (source, scene, rootUrl) {
  30999. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  31000. };
  31001. return PBRMaterial;
  31002. }(BABYLON.PBRBaseMaterial));
  31003. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  31004. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  31005. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  31006. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  31007. __decorate([
  31008. BABYLON.serialize(),
  31009. BABYLON.expandToProperty(null)
  31010. ], PBRMaterial.prototype, "directIntensity", void 0);
  31011. __decorate([
  31012. BABYLON.serialize(),
  31013. BABYLON.expandToProperty(null)
  31014. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  31015. __decorate([
  31016. BABYLON.serialize(),
  31017. BABYLON.expandToProperty(null)
  31018. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  31019. __decorate([
  31020. BABYLON.serialize(),
  31021. BABYLON.expandToProperty(null)
  31022. ], PBRMaterial.prototype, "specularIntensity", void 0);
  31023. __decorate([
  31024. BABYLON.serialize(),
  31025. BABYLON.expandToProperty(null)
  31026. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  31027. __decorate([
  31028. BABYLON.serialize(),
  31029. BABYLON.expandToProperty(null)
  31030. ], PBRMaterial.prototype, "cameraExposure", void 0);
  31031. __decorate([
  31032. BABYLON.serialize(),
  31033. BABYLON.expandToProperty(null)
  31034. ], PBRMaterial.prototype, "cameraContrast", void 0);
  31035. __decorate([
  31036. BABYLON.serializeAsTexture(),
  31037. BABYLON.expandToProperty(null)
  31038. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  31039. __decorate([
  31040. BABYLON.serializeAsColorCurves(),
  31041. BABYLON.expandToProperty(null)
  31042. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  31043. __decorate([
  31044. BABYLON.serializeAsTexture(),
  31045. BABYLON.expandToProperty(null)
  31046. ], PBRMaterial.prototype, "albedoTexture", void 0);
  31047. __decorate([
  31048. BABYLON.serializeAsTexture(),
  31049. BABYLON.expandToProperty(null)
  31050. ], PBRMaterial.prototype, "ambientTexture", void 0);
  31051. __decorate([
  31052. BABYLON.serialize(),
  31053. BABYLON.expandToProperty(null)
  31054. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  31055. __decorate([
  31056. BABYLON.serializeAsTexture(),
  31057. BABYLON.expandToProperty(null)
  31058. ], PBRMaterial.prototype, "opacityTexture", void 0);
  31059. __decorate([
  31060. BABYLON.serializeAsTexture(),
  31061. BABYLON.expandToProperty(null)
  31062. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  31063. __decorate([
  31064. BABYLON.serializeAsTexture(),
  31065. BABYLON.expandToProperty(null)
  31066. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  31067. __decorate([
  31068. BABYLON.serializeAsTexture(),
  31069. BABYLON.expandToProperty(null)
  31070. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  31071. __decorate([
  31072. BABYLON.serializeAsTexture(),
  31073. BABYLON.expandToProperty(null)
  31074. ], PBRMaterial.prototype, "metallicTexture", void 0);
  31075. __decorate([
  31076. BABYLON.serialize(),
  31077. BABYLON.expandToProperty(null)
  31078. ], PBRMaterial.prototype, "metallic", void 0);
  31079. __decorate([
  31080. BABYLON.serialize(),
  31081. BABYLON.expandToProperty(null)
  31082. ], PBRMaterial.prototype, "roughness", void 0);
  31083. __decorate([
  31084. BABYLON.serializeAsTexture(),
  31085. BABYLON.expandToProperty(null)
  31086. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  31087. __decorate([
  31088. BABYLON.serializeAsTexture(),
  31089. BABYLON.expandToProperty(null)
  31090. ], PBRMaterial.prototype, "bumpTexture", void 0);
  31091. __decorate([
  31092. BABYLON.serializeAsTexture(),
  31093. BABYLON.expandToProperty(null)
  31094. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  31095. __decorate([
  31096. BABYLON.serializeAsTexture(),
  31097. BABYLON.expandToProperty(null)
  31098. ], PBRMaterial.prototype, "refractionTexture", void 0);
  31099. __decorate([
  31100. BABYLON.serializeAsColor3("ambient"),
  31101. BABYLON.expandToProperty(null)
  31102. ], PBRMaterial.prototype, "ambientColor", void 0);
  31103. __decorate([
  31104. BABYLON.serializeAsColor3("albedo"),
  31105. BABYLON.expandToProperty(null)
  31106. ], PBRMaterial.prototype, "albedoColor", void 0);
  31107. __decorate([
  31108. BABYLON.serializeAsColor3("reflectivity"),
  31109. BABYLON.expandToProperty(null)
  31110. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  31111. __decorate([
  31112. BABYLON.serializeAsColor3("reflection"),
  31113. BABYLON.expandToProperty(null)
  31114. ], PBRMaterial.prototype, "reflectionColor", void 0);
  31115. __decorate([
  31116. BABYLON.serializeAsColor3("emissive"),
  31117. BABYLON.expandToProperty(null)
  31118. ], PBRMaterial.prototype, "emissiveColor", void 0);
  31119. __decorate([
  31120. BABYLON.serialize(),
  31121. BABYLON.expandToProperty(null)
  31122. ], PBRMaterial.prototype, "microSurface", void 0);
  31123. __decorate([
  31124. BABYLON.serialize(),
  31125. BABYLON.expandToProperty(null)
  31126. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  31127. __decorate([
  31128. BABYLON.serialize(),
  31129. BABYLON.expandToProperty(null)
  31130. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  31131. __decorate([
  31132. BABYLON.serializeAsFresnelParameters(),
  31133. BABYLON.expandToProperty(null)
  31134. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  31135. __decorate([
  31136. BABYLON.serializeAsFresnelParameters(),
  31137. BABYLON.expandToProperty(null)
  31138. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  31139. __decorate([
  31140. BABYLON.serialize(),
  31141. BABYLON.expandToProperty(null)
  31142. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  31143. __decorate([
  31144. BABYLON.serialize(),
  31145. BABYLON.expandToProperty(null)
  31146. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31147. __decorate([
  31148. BABYLON.serialize(),
  31149. BABYLON.expandToProperty(null)
  31150. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31151. __decorate([
  31152. BABYLON.serialize(),
  31153. BABYLON.expandToProperty(null)
  31154. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  31155. __decorate([
  31156. BABYLON.serialize(),
  31157. BABYLON.expandToProperty(null)
  31158. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  31159. __decorate([
  31160. BABYLON.serialize(),
  31161. BABYLON.expandToProperty(null)
  31162. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  31163. __decorate([
  31164. BABYLON.serialize(),
  31165. BABYLON.expandToProperty(null)
  31166. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  31167. __decorate([
  31168. BABYLON.serialize(),
  31169. BABYLON.expandToProperty(null)
  31170. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  31171. __decorate([
  31172. BABYLON.serialize(),
  31173. BABYLON.expandToProperty(null)
  31174. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  31175. __decorate([
  31176. BABYLON.serialize(),
  31177. BABYLON.expandToProperty(null)
  31178. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  31179. __decorate([
  31180. BABYLON.serialize(),
  31181. BABYLON.expandToProperty(null)
  31182. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  31183. __decorate([
  31184. BABYLON.serialize(),
  31185. BABYLON.expandToProperty(null)
  31186. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  31187. __decorate([
  31188. BABYLON.serialize(),
  31189. BABYLON.expandToProperty(null)
  31190. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  31191. __decorate([
  31192. BABYLON.serialize(),
  31193. BABYLON.expandToProperty(null)
  31194. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  31195. __decorate([
  31196. BABYLON.serialize(),
  31197. BABYLON.expandToProperty(null)
  31198. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  31199. __decorate([
  31200. BABYLON.serialize(),
  31201. BABYLON.expandToProperty(null)
  31202. ], PBRMaterial.prototype, "useParallax", void 0);
  31203. __decorate([
  31204. BABYLON.serialize(),
  31205. BABYLON.expandToProperty(null)
  31206. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  31207. __decorate([
  31208. BABYLON.serialize(),
  31209. BABYLON.expandToProperty(null)
  31210. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  31211. __decorate([
  31212. BABYLON.serialize(),
  31213. BABYLON.expandToProperty(null)
  31214. ], PBRMaterial.prototype, "disableLighting", void 0);
  31215. __decorate([
  31216. BABYLON.serialize(),
  31217. BABYLON.expandToProperty(null)
  31218. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  31219. __decorate([
  31220. BABYLON.serialize(),
  31221. BABYLON.expandToProperty(null)
  31222. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  31223. __decorate([
  31224. BABYLON.serialize(),
  31225. BABYLON.expandToProperty(null)
  31226. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  31227. __decorate([
  31228. BABYLON.serialize(),
  31229. BABYLON.expandToProperty(null)
  31230. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  31231. BABYLON.PBRMaterial = PBRMaterial;
  31232. })(BABYLON || (BABYLON = {}));
  31233. //# sourceMappingURL=babylon.pbrMaterial.js.map
  31234. var BABYLON;
  31235. (function (BABYLON) {
  31236. /**
  31237. * The PBR material of BJS following the metal roughness convention.
  31238. *
  31239. * This fits to the define PBR convention in the GLTF definition:
  31240. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  31241. */
  31242. var PBRMetallicRoughnessMaterial = (function (_super) {
  31243. __extends(PBRMetallicRoughnessMaterial, _super);
  31244. /**
  31245. * Instantiates a new PBRMetalRoughnessMaterial instance.
  31246. *
  31247. * @param name The material name
  31248. * @param scene The scene the material will be use in.
  31249. */
  31250. function PBRMetallicRoughnessMaterial(name, scene) {
  31251. var _this = _super.call(this, name, scene) || this;
  31252. _this._useRoughnessFromMetallicTextureGreen = true;
  31253. _this._useMetallnessFromMetallicTextureBlue = true;
  31254. return _this;
  31255. }
  31256. /**
  31257. * Return the currrent class name of the material.
  31258. */
  31259. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  31260. return "PBRMetallicRoughnessMaterial";
  31261. };
  31262. /**
  31263. * Serialize the material to a parsable JSON object.
  31264. */
  31265. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  31266. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31267. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  31268. return serializationObject;
  31269. };
  31270. /**
  31271. * Parses a JSON object correponding to the serialize function.
  31272. */
  31273. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  31274. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  31275. };
  31276. return PBRMetallicRoughnessMaterial;
  31277. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31278. __decorate([
  31279. BABYLON.serializeAsTexture(),
  31280. BABYLON.expandToProperty(null, "_albedoColor")
  31281. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  31282. __decorate([
  31283. BABYLON.serializeAsTexture(),
  31284. BABYLON.expandToProperty(null, "_albedoTexture")
  31285. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  31286. __decorate([
  31287. BABYLON.serialize(),
  31288. BABYLON.expandToProperty(null)
  31289. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  31290. __decorate([
  31291. BABYLON.serialize(),
  31292. BABYLON.expandToProperty(null)
  31293. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  31294. __decorate([
  31295. BABYLON.serializeAsTexture(),
  31296. BABYLON.expandToProperty(null, "_metallicTexture")
  31297. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  31298. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  31299. })(BABYLON || (BABYLON = {}));
  31300. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  31301. var BABYLON;
  31302. (function (BABYLON) {
  31303. /**
  31304. * The PBR material of BJS following the specular glossiness convention.
  31305. *
  31306. * This fits to the define PBR convention in the GLTF definition:
  31307. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  31308. */
  31309. var PBRSpecularGlossinessMaterial = (function (_super) {
  31310. __extends(PBRSpecularGlossinessMaterial, _super);
  31311. /**
  31312. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  31313. *
  31314. * @param name The material name
  31315. * @param scene The scene the material will be use in.
  31316. */
  31317. function PBRSpecularGlossinessMaterial(name, scene) {
  31318. var _this = _super.call(this, name, scene) || this;
  31319. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  31320. return _this;
  31321. }
  31322. /**
  31323. * Return the currrent class name of the material.
  31324. */
  31325. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  31326. return "PBRSpecularGlossinessMaterial";
  31327. };
  31328. /**
  31329. * Serialize the material to a parsable JSON object.
  31330. */
  31331. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  31332. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31333. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  31334. return serializationObject;
  31335. };
  31336. /**
  31337. * Parses a JSON object correponding to the serialize function.
  31338. */
  31339. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  31340. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  31341. };
  31342. return PBRSpecularGlossinessMaterial;
  31343. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31344. __decorate([
  31345. BABYLON.serializeAsColor3(),
  31346. BABYLON.expandToProperty(null, "_albedoColor")
  31347. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  31348. __decorate([
  31349. BABYLON.serializeAsTexture(),
  31350. BABYLON.expandToProperty(null, "_albedoTexture")
  31351. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  31352. __decorate([
  31353. BABYLON.serializeAsColor3(),
  31354. BABYLON.expandToProperty(null, "_reflectivityColor")
  31355. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  31356. __decorate([
  31357. BABYLON.serialize(),
  31358. BABYLON.expandToProperty(null, "_microSurface")
  31359. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  31360. __decorate([
  31361. BABYLON.serializeAsTexture(),
  31362. BABYLON.expandToProperty(null, "_reflectivityTexture")
  31363. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  31364. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  31365. })(BABYLON || (BABYLON = {}));
  31366. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  31367. var BABYLON;
  31368. (function (BABYLON) {
  31369. BABYLON.CameraInputTypes = {};
  31370. var CameraInputsManager = (function () {
  31371. function CameraInputsManager(camera) {
  31372. this.attached = {};
  31373. this.camera = camera;
  31374. this.checkInputs = function () { };
  31375. }
  31376. CameraInputsManager.prototype.add = function (input) {
  31377. var type = input.getSimpleName();
  31378. if (this.attached[type]) {
  31379. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31380. return;
  31381. }
  31382. this.attached[type] = input;
  31383. input.camera = this.camera;
  31384. //for checkInputs, we are dynamically creating a function
  31385. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31386. if (input.checkInputs) {
  31387. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31388. }
  31389. if (this.attachedElement) {
  31390. input.attachControl(this.attachedElement);
  31391. }
  31392. };
  31393. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31394. for (var cam in this.attached) {
  31395. var input = this.attached[cam];
  31396. if (input === inputToRemove) {
  31397. input.detachControl(this.attachedElement);
  31398. delete this.attached[cam];
  31399. this.rebuildInputCheck();
  31400. }
  31401. }
  31402. };
  31403. CameraInputsManager.prototype.removeByType = function (inputType) {
  31404. for (var cam in this.attached) {
  31405. var input = this.attached[cam];
  31406. if (input.getTypeName() === inputType) {
  31407. input.detachControl(this.attachedElement);
  31408. delete this.attached[cam];
  31409. this.rebuildInputCheck();
  31410. }
  31411. }
  31412. };
  31413. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31414. var current = this.checkInputs;
  31415. return function () {
  31416. current();
  31417. fn();
  31418. };
  31419. };
  31420. CameraInputsManager.prototype.attachInput = function (input) {
  31421. input.attachControl(this.attachedElement, this.noPreventDefault);
  31422. };
  31423. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31424. if (this.attachedElement) {
  31425. return;
  31426. }
  31427. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31428. this.attachedElement = element;
  31429. this.noPreventDefault = noPreventDefault;
  31430. for (var cam in this.attached) {
  31431. var input = this.attached[cam];
  31432. this.attached[cam].attachControl(element, noPreventDefault);
  31433. }
  31434. };
  31435. CameraInputsManager.prototype.detachElement = function (element) {
  31436. if (this.attachedElement !== element) {
  31437. return;
  31438. }
  31439. for (var cam in this.attached) {
  31440. var input = this.attached[cam];
  31441. this.attached[cam].detachControl(element);
  31442. }
  31443. this.attachedElement = null;
  31444. };
  31445. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31446. this.checkInputs = function () { };
  31447. for (var cam in this.attached) {
  31448. var input = this.attached[cam];
  31449. if (input.checkInputs) {
  31450. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31451. }
  31452. }
  31453. };
  31454. CameraInputsManager.prototype.clear = function () {
  31455. if (this.attachedElement) {
  31456. this.detachElement(this.attachedElement);
  31457. }
  31458. this.attached = {};
  31459. this.attachedElement = null;
  31460. this.checkInputs = function () { };
  31461. };
  31462. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31463. var inputs = {};
  31464. for (var cam in this.attached) {
  31465. var input = this.attached[cam];
  31466. var res = BABYLON.SerializationHelper.Serialize(input);
  31467. inputs[input.getTypeName()] = res;
  31468. }
  31469. serializedCamera.inputsmgr = inputs;
  31470. };
  31471. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31472. var parsedInputs = parsedCamera.inputsmgr;
  31473. if (parsedInputs) {
  31474. this.clear();
  31475. for (var n in parsedInputs) {
  31476. var construct = BABYLON.CameraInputTypes[n];
  31477. if (construct) {
  31478. var parsedinput = parsedInputs[n];
  31479. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31480. this.add(input);
  31481. }
  31482. }
  31483. }
  31484. else {
  31485. //2016-03-08 this part is for managing backward compatibility
  31486. for (var n in this.attached) {
  31487. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  31488. if (construct) {
  31489. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31490. this.remove(this.attached[n]);
  31491. this.add(input);
  31492. }
  31493. }
  31494. }
  31495. };
  31496. return CameraInputsManager;
  31497. }());
  31498. BABYLON.CameraInputsManager = CameraInputsManager;
  31499. })(BABYLON || (BABYLON = {}));
  31500. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31501. var BABYLON;
  31502. (function (BABYLON) {
  31503. var FreeCameraMouseInput = (function () {
  31504. function FreeCameraMouseInput(touchEnabled) {
  31505. if (touchEnabled === void 0) { touchEnabled = true; }
  31506. this.touchEnabled = touchEnabled;
  31507. this.buttons = [0, 1, 2];
  31508. this.angularSensibility = 2000.0;
  31509. }
  31510. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  31511. var _this = this;
  31512. var engine = this.camera.getEngine();
  31513. if (!this._pointerInput) {
  31514. this._pointerInput = function (p, s) {
  31515. var evt = p.event;
  31516. if (!_this.touchEnabled && evt.pointerType === "touch") {
  31517. return;
  31518. }
  31519. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31520. return;
  31521. }
  31522. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31523. try {
  31524. evt.srcElement.setPointerCapture(evt.pointerId);
  31525. }
  31526. catch (e) {
  31527. //Nothing to do with the error. Execution will continue.
  31528. }
  31529. _this.previousPosition = {
  31530. x: evt.clientX,
  31531. y: evt.clientY
  31532. };
  31533. if (!noPreventDefault) {
  31534. evt.preventDefault();
  31535. element.focus();
  31536. }
  31537. }
  31538. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31539. try {
  31540. evt.srcElement.releasePointerCapture(evt.pointerId);
  31541. }
  31542. catch (e) {
  31543. //Nothing to do with the error.
  31544. }
  31545. _this.previousPosition = null;
  31546. if (!noPreventDefault) {
  31547. evt.preventDefault();
  31548. }
  31549. }
  31550. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  31551. if (!_this.previousPosition || engine.isPointerLock) {
  31552. return;
  31553. }
  31554. var offsetX = evt.clientX - _this.previousPosition.x;
  31555. var offsetY = evt.clientY - _this.previousPosition.y;
  31556. if (_this.camera.getScene().useRightHandedSystem) {
  31557. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  31558. }
  31559. else {
  31560. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  31561. }
  31562. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  31563. _this.previousPosition = {
  31564. x: evt.clientX,
  31565. y: evt.clientY
  31566. };
  31567. if (!noPreventDefault) {
  31568. evt.preventDefault();
  31569. }
  31570. }
  31571. };
  31572. }
  31573. this._onMouseMove = function (evt) {
  31574. if (!engine.isPointerLock) {
  31575. return;
  31576. }
  31577. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31578. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31579. if (_this.camera.getScene().useRightHandedSystem) {
  31580. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  31581. }
  31582. else {
  31583. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  31584. }
  31585. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  31586. _this.previousPosition = null;
  31587. if (!noPreventDefault) {
  31588. evt.preventDefault();
  31589. }
  31590. };
  31591. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31592. element.addEventListener("mousemove", this._onMouseMove, false);
  31593. };
  31594. FreeCameraMouseInput.prototype.detachControl = function (element) {
  31595. if (this._observer && element) {
  31596. this.camera.getScene().onPointerObservable.remove(this._observer);
  31597. element.removeEventListener("mousemove", this._onMouseMove);
  31598. this._observer = null;
  31599. this._onMouseMove = null;
  31600. this.previousPosition = null;
  31601. }
  31602. };
  31603. FreeCameraMouseInput.prototype.getTypeName = function () {
  31604. return "FreeCameraMouseInput";
  31605. };
  31606. FreeCameraMouseInput.prototype.getSimpleName = function () {
  31607. return "mouse";
  31608. };
  31609. return FreeCameraMouseInput;
  31610. }());
  31611. __decorate([
  31612. BABYLON.serialize()
  31613. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  31614. __decorate([
  31615. BABYLON.serialize()
  31616. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  31617. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  31618. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  31619. })(BABYLON || (BABYLON = {}));
  31620. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  31621. var BABYLON;
  31622. (function (BABYLON) {
  31623. var FreeCameraKeyboardMoveInput = (function () {
  31624. function FreeCameraKeyboardMoveInput() {
  31625. this._keys = [];
  31626. this.keysUp = [38];
  31627. this.keysDown = [40];
  31628. this.keysLeft = [37];
  31629. this.keysRight = [39];
  31630. }
  31631. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31632. var _this = this;
  31633. if (!this._onKeyDown) {
  31634. element.tabIndex = 1;
  31635. this._onKeyDown = function (evt) {
  31636. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31637. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31638. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31639. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31640. var index = _this._keys.indexOf(evt.keyCode);
  31641. if (index === -1) {
  31642. _this._keys.push(evt.keyCode);
  31643. }
  31644. if (!noPreventDefault) {
  31645. evt.preventDefault();
  31646. }
  31647. }
  31648. };
  31649. this._onKeyUp = function (evt) {
  31650. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31651. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31652. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31653. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31654. var index = _this._keys.indexOf(evt.keyCode);
  31655. if (index >= 0) {
  31656. _this._keys.splice(index, 1);
  31657. }
  31658. if (!noPreventDefault) {
  31659. evt.preventDefault();
  31660. }
  31661. }
  31662. };
  31663. element.addEventListener("keydown", this._onKeyDown, false);
  31664. element.addEventListener("keyup", this._onKeyUp, false);
  31665. BABYLON.Tools.RegisterTopRootEvents([
  31666. { name: "blur", handler: this._onLostFocus }
  31667. ]);
  31668. }
  31669. };
  31670. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31671. if (this._onKeyDown) {
  31672. element.removeEventListener("keydown", this._onKeyDown);
  31673. element.removeEventListener("keyup", this._onKeyUp);
  31674. BABYLON.Tools.UnregisterTopRootEvents([
  31675. { name: "blur", handler: this._onLostFocus }
  31676. ]);
  31677. this._keys = [];
  31678. this._onKeyDown = null;
  31679. this._onKeyUp = null;
  31680. }
  31681. };
  31682. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31683. if (this._onKeyDown) {
  31684. var camera = this.camera;
  31685. // Keyboard
  31686. for (var index = 0; index < this._keys.length; index++) {
  31687. var keyCode = this._keys[index];
  31688. var speed = camera._computeLocalCameraSpeed();
  31689. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31690. camera._localDirection.copyFromFloats(-speed, 0, 0);
  31691. }
  31692. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31693. camera._localDirection.copyFromFloats(0, 0, speed);
  31694. }
  31695. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31696. camera._localDirection.copyFromFloats(speed, 0, 0);
  31697. }
  31698. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31699. camera._localDirection.copyFromFloats(0, 0, -speed);
  31700. }
  31701. if (camera.getScene().useRightHandedSystem) {
  31702. camera._localDirection.z *= -1;
  31703. }
  31704. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  31705. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  31706. camera.cameraDirection.addInPlace(camera._transformedDirection);
  31707. }
  31708. }
  31709. };
  31710. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  31711. return "FreeCameraKeyboardMoveInput";
  31712. };
  31713. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  31714. this._keys = [];
  31715. };
  31716. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31717. return "keyboard";
  31718. };
  31719. return FreeCameraKeyboardMoveInput;
  31720. }());
  31721. __decorate([
  31722. BABYLON.serialize()
  31723. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31724. __decorate([
  31725. BABYLON.serialize()
  31726. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  31727. __decorate([
  31728. BABYLON.serialize()
  31729. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  31730. __decorate([
  31731. BABYLON.serialize()
  31732. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  31733. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  31734. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  31735. })(BABYLON || (BABYLON = {}));
  31736. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  31737. var BABYLON;
  31738. (function (BABYLON) {
  31739. var FreeCameraInputsManager = (function (_super) {
  31740. __extends(FreeCameraInputsManager, _super);
  31741. function FreeCameraInputsManager(camera) {
  31742. return _super.call(this, camera) || this;
  31743. }
  31744. FreeCameraInputsManager.prototype.addKeyboard = function () {
  31745. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  31746. return this;
  31747. };
  31748. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  31749. if (touchEnabled === void 0) { touchEnabled = true; }
  31750. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  31751. return this;
  31752. };
  31753. FreeCameraInputsManager.prototype.addGamepad = function () {
  31754. this.add(new BABYLON.FreeCameraGamepadInput());
  31755. return this;
  31756. };
  31757. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  31758. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  31759. return this;
  31760. };
  31761. FreeCameraInputsManager.prototype.addTouch = function () {
  31762. this.add(new BABYLON.FreeCameraTouchInput());
  31763. return this;
  31764. };
  31765. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  31766. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  31767. return this;
  31768. };
  31769. return FreeCameraInputsManager;
  31770. }(BABYLON.CameraInputsManager));
  31771. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  31772. })(BABYLON || (BABYLON = {}));
  31773. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  31774. /// <reference path="babylon.camera.ts" />
  31775. var BABYLON;
  31776. (function (BABYLON) {
  31777. var TargetCamera = (function (_super) {
  31778. __extends(TargetCamera, _super);
  31779. function TargetCamera(name, position, scene) {
  31780. var _this = _super.call(this, name, position, scene) || this;
  31781. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31782. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31783. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31784. _this.speed = 2.0;
  31785. _this.noRotationConstraint = false;
  31786. _this.lockedTarget = null;
  31787. _this._currentTarget = BABYLON.Vector3.Zero();
  31788. _this._viewMatrix = BABYLON.Matrix.Zero();
  31789. _this._camMatrix = BABYLON.Matrix.Zero();
  31790. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31791. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31792. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31793. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31794. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31795. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31796. _this._tempMatrix = BABYLON.Matrix.Zero();
  31797. return _this;
  31798. }
  31799. TargetCamera.prototype.getFrontPosition = function (distance) {
  31800. var direction = this.getTarget().subtract(this.position);
  31801. direction.normalize();
  31802. direction.scaleInPlace(distance);
  31803. return this.globalPosition.add(direction);
  31804. };
  31805. TargetCamera.prototype._getLockedTargetPosition = function () {
  31806. if (!this.lockedTarget) {
  31807. return null;
  31808. }
  31809. if (this.lockedTarget.absolutePosition) {
  31810. this.lockedTarget.computeWorldMatrix();
  31811. }
  31812. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31813. };
  31814. // Cache
  31815. TargetCamera.prototype._initCache = function () {
  31816. _super.prototype._initCache.call(this);
  31817. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31818. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31819. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31820. };
  31821. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31822. if (!ignoreParentClass) {
  31823. _super.prototype._updateCache.call(this);
  31824. }
  31825. var lockedTargetPosition = this._getLockedTargetPosition();
  31826. if (!lockedTargetPosition) {
  31827. this._cache.lockedTarget = null;
  31828. }
  31829. else {
  31830. if (!this._cache.lockedTarget) {
  31831. this._cache.lockedTarget = lockedTargetPosition.clone();
  31832. }
  31833. else {
  31834. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31835. }
  31836. }
  31837. this._cache.rotation.copyFrom(this.rotation);
  31838. if (this.rotationQuaternion)
  31839. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31840. };
  31841. // Synchronized
  31842. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31843. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31844. return false;
  31845. }
  31846. var lockedTargetPosition = this._getLockedTargetPosition();
  31847. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31848. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31849. };
  31850. // Methods
  31851. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31852. var engine = this.getEngine();
  31853. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31854. };
  31855. // Target
  31856. TargetCamera.prototype.setTarget = function (target) {
  31857. this.upVector.normalize();
  31858. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31859. this._camMatrix.invert();
  31860. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31861. var vDir = target.subtract(this.position);
  31862. if (vDir.x >= 0.0) {
  31863. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31864. }
  31865. else {
  31866. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31867. }
  31868. this.rotation.z = 0;
  31869. if (isNaN(this.rotation.x)) {
  31870. this.rotation.x = 0;
  31871. }
  31872. if (isNaN(this.rotation.y)) {
  31873. this.rotation.y = 0;
  31874. }
  31875. if (isNaN(this.rotation.z)) {
  31876. this.rotation.z = 0;
  31877. }
  31878. if (this.rotationQuaternion) {
  31879. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31880. }
  31881. };
  31882. /**
  31883. * Return the current target position of the camera. This value is expressed in local space.
  31884. */
  31885. TargetCamera.prototype.getTarget = function () {
  31886. return this._currentTarget;
  31887. };
  31888. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31889. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31890. };
  31891. TargetCamera.prototype._updatePosition = function () {
  31892. if (this.parent) {
  31893. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31894. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31895. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31896. return;
  31897. }
  31898. this.position.addInPlace(this.cameraDirection);
  31899. };
  31900. TargetCamera.prototype._checkInputs = function () {
  31901. var needToMove = this._decideIfNeedsToMove();
  31902. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31903. // Move
  31904. if (needToMove) {
  31905. this._updatePosition();
  31906. }
  31907. // Rotate
  31908. if (needToRotate) {
  31909. this.rotation.x += this.cameraRotation.x;
  31910. this.rotation.y += this.cameraRotation.y;
  31911. //rotate, if quaternion is set and rotation was used
  31912. if (this.rotationQuaternion) {
  31913. var len = this.rotation.lengthSquared();
  31914. if (len) {
  31915. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31916. }
  31917. }
  31918. if (!this.noRotationConstraint) {
  31919. var limit = (Math.PI / 2) * 0.95;
  31920. if (this.rotation.x > limit)
  31921. this.rotation.x = limit;
  31922. if (this.rotation.x < -limit)
  31923. this.rotation.x = -limit;
  31924. }
  31925. }
  31926. // Inertia
  31927. if (needToMove) {
  31928. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31929. this.cameraDirection.x = 0;
  31930. }
  31931. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31932. this.cameraDirection.y = 0;
  31933. }
  31934. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31935. this.cameraDirection.z = 0;
  31936. }
  31937. this.cameraDirection.scaleInPlace(this.inertia);
  31938. }
  31939. if (needToRotate) {
  31940. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31941. this.cameraRotation.x = 0;
  31942. }
  31943. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31944. this.cameraRotation.y = 0;
  31945. }
  31946. this.cameraRotation.scaleInPlace(this.inertia);
  31947. }
  31948. _super.prototype._checkInputs.call(this);
  31949. };
  31950. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31951. if (this.rotationQuaternion) {
  31952. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31953. //update the up vector!
  31954. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31955. }
  31956. else {
  31957. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31958. }
  31959. };
  31960. TargetCamera.prototype._getViewMatrix = function () {
  31961. if (!this.lockedTarget) {
  31962. // Compute
  31963. this._updateCameraRotationMatrix();
  31964. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31965. // Computing target and final matrix
  31966. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31967. }
  31968. else {
  31969. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31970. }
  31971. if (this.getScene().useRightHandedSystem) {
  31972. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31973. }
  31974. else {
  31975. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31976. }
  31977. return this._viewMatrix;
  31978. };
  31979. /**
  31980. * @override
  31981. * Override Camera.createRigCamera
  31982. */
  31983. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31984. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31985. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31986. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31987. if (!this.rotationQuaternion) {
  31988. this.rotationQuaternion = new BABYLON.Quaternion();
  31989. }
  31990. rigCamera._cameraRigParams = {};
  31991. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31992. }
  31993. return rigCamera;
  31994. }
  31995. return null;
  31996. };
  31997. /**
  31998. * @override
  31999. * Override Camera._updateRigCameras
  32000. */
  32001. TargetCamera.prototype._updateRigCameras = function () {
  32002. var camLeft = this._rigCameras[0];
  32003. var camRight = this._rigCameras[1];
  32004. switch (this.cameraRigMode) {
  32005. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32006. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32007. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32008. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32009. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  32010. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  32011. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  32012. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  32013. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  32014. camLeft.setTarget(this.getTarget());
  32015. camRight.setTarget(this.getTarget());
  32016. break;
  32017. case BABYLON.Camera.RIG_MODE_VR:
  32018. if (camLeft.rotationQuaternion) {
  32019. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  32020. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  32021. }
  32022. else {
  32023. camLeft.rotation.copyFrom(this.rotation);
  32024. camRight.rotation.copyFrom(this.rotation);
  32025. }
  32026. camLeft.position.copyFrom(this.position);
  32027. camRight.position.copyFrom(this.position);
  32028. break;
  32029. }
  32030. _super.prototype._updateRigCameras.call(this);
  32031. };
  32032. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  32033. if (!this._rigCamTransformMatrix) {
  32034. this._rigCamTransformMatrix = new BABYLON.Matrix();
  32035. }
  32036. var target = this.getTarget();
  32037. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  32038. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  32039. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  32040. };
  32041. TargetCamera.prototype.getClassName = function () {
  32042. return "TargetCamera";
  32043. };
  32044. return TargetCamera;
  32045. }(BABYLON.Camera));
  32046. __decorate([
  32047. BABYLON.serializeAsVector3()
  32048. ], TargetCamera.prototype, "rotation", void 0);
  32049. __decorate([
  32050. BABYLON.serialize()
  32051. ], TargetCamera.prototype, "speed", void 0);
  32052. __decorate([
  32053. BABYLON.serializeAsMeshReference("lockedTargetId")
  32054. ], TargetCamera.prototype, "lockedTarget", void 0);
  32055. BABYLON.TargetCamera = TargetCamera;
  32056. })(BABYLON || (BABYLON = {}));
  32057. //# sourceMappingURL=babylon.targetCamera.js.map
  32058. var BABYLON;
  32059. (function (BABYLON) {
  32060. var FreeCamera = (function (_super) {
  32061. __extends(FreeCamera, _super);
  32062. function FreeCamera(name, position, scene) {
  32063. var _this = _super.call(this, name, position, scene) || this;
  32064. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  32065. _this.checkCollisions = false;
  32066. _this.applyGravity = false;
  32067. _this._needMoveForGravity = false;
  32068. _this._oldPosition = BABYLON.Vector3.Zero();
  32069. _this._diffPosition = BABYLON.Vector3.Zero();
  32070. _this._newPosition = BABYLON.Vector3.Zero();
  32071. // Collisions
  32072. _this._collisionMask = -1;
  32073. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32074. if (collidedMesh === void 0) { collidedMesh = null; }
  32075. //TODO move this to the collision coordinator!
  32076. if (_this.getScene().workerCollisions)
  32077. newPosition.multiplyInPlace(_this._collider.radius);
  32078. var updatePosition = function (newPos) {
  32079. _this._newPosition.copyFrom(newPos);
  32080. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  32081. var oldPosition = _this.position.clone();
  32082. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  32083. _this.position.addInPlace(_this._diffPosition);
  32084. if (_this.onCollide && collidedMesh) {
  32085. _this.onCollide(collidedMesh);
  32086. }
  32087. }
  32088. };
  32089. updatePosition(newPosition);
  32090. };
  32091. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  32092. _this.inputs.addKeyboard().addMouse();
  32093. return _this;
  32094. }
  32095. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  32096. //-- begin properties for backward compatibility for inputs
  32097. get: function () {
  32098. var mouse = this.inputs.attached["mouse"];
  32099. if (mouse)
  32100. return mouse.angularSensibility;
  32101. },
  32102. set: function (value) {
  32103. var mouse = this.inputs.attached["mouse"];
  32104. if (mouse)
  32105. mouse.angularSensibility = value;
  32106. },
  32107. enumerable: true,
  32108. configurable: true
  32109. });
  32110. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  32111. get: function () {
  32112. var keyboard = this.inputs.attached["keyboard"];
  32113. if (keyboard)
  32114. return keyboard.keysUp;
  32115. },
  32116. set: function (value) {
  32117. var keyboard = this.inputs.attached["keyboard"];
  32118. if (keyboard)
  32119. keyboard.keysUp = value;
  32120. },
  32121. enumerable: true,
  32122. configurable: true
  32123. });
  32124. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  32125. get: function () {
  32126. var keyboard = this.inputs.attached["keyboard"];
  32127. if (keyboard)
  32128. return keyboard.keysDown;
  32129. },
  32130. set: function (value) {
  32131. var keyboard = this.inputs.attached["keyboard"];
  32132. if (keyboard)
  32133. keyboard.keysDown = value;
  32134. },
  32135. enumerable: true,
  32136. configurable: true
  32137. });
  32138. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  32139. get: function () {
  32140. var keyboard = this.inputs.attached["keyboard"];
  32141. if (keyboard)
  32142. return keyboard.keysLeft;
  32143. },
  32144. set: function (value) {
  32145. var keyboard = this.inputs.attached["keyboard"];
  32146. if (keyboard)
  32147. keyboard.keysLeft = value;
  32148. },
  32149. enumerable: true,
  32150. configurable: true
  32151. });
  32152. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  32153. get: function () {
  32154. var keyboard = this.inputs.attached["keyboard"];
  32155. if (keyboard)
  32156. return keyboard.keysRight;
  32157. },
  32158. set: function (value) {
  32159. var keyboard = this.inputs.attached["keyboard"];
  32160. if (keyboard)
  32161. keyboard.keysRight = value;
  32162. },
  32163. enumerable: true,
  32164. configurable: true
  32165. });
  32166. // Controls
  32167. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32168. this.inputs.attachElement(element, noPreventDefault);
  32169. };
  32170. FreeCamera.prototype.detachControl = function (element) {
  32171. this.inputs.detachElement(element);
  32172. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  32173. this.cameraRotation = new BABYLON.Vector2(0, 0);
  32174. };
  32175. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  32176. get: function () {
  32177. return this._collisionMask;
  32178. },
  32179. set: function (mask) {
  32180. this._collisionMask = !isNaN(mask) ? mask : -1;
  32181. },
  32182. enumerable: true,
  32183. configurable: true
  32184. });
  32185. FreeCamera.prototype._collideWithWorld = function (velocity) {
  32186. var globalPosition;
  32187. if (this.parent) {
  32188. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  32189. }
  32190. else {
  32191. globalPosition = this.position;
  32192. }
  32193. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  32194. if (!this._collider) {
  32195. this._collider = new BABYLON.Collider();
  32196. }
  32197. this._collider.radius = this.ellipsoid;
  32198. this._collider.collisionMask = this._collisionMask;
  32199. //no need for clone, as long as gravity is not on.
  32200. var actualVelocity = velocity;
  32201. //add gravity to the velocity to prevent the dual-collision checking
  32202. if (this.applyGravity) {
  32203. //this prevents mending with cameraDirection, a global variable of the free camera class.
  32204. actualVelocity = velocity.add(this.getScene().gravity);
  32205. }
  32206. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32207. };
  32208. FreeCamera.prototype._checkInputs = function () {
  32209. if (!this._localDirection) {
  32210. this._localDirection = BABYLON.Vector3.Zero();
  32211. this._transformedDirection = BABYLON.Vector3.Zero();
  32212. }
  32213. this.inputs.checkInputs();
  32214. _super.prototype._checkInputs.call(this);
  32215. };
  32216. FreeCamera.prototype._decideIfNeedsToMove = function () {
  32217. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  32218. };
  32219. FreeCamera.prototype._updatePosition = function () {
  32220. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  32221. this._collideWithWorld(this.cameraDirection);
  32222. }
  32223. else {
  32224. _super.prototype._updatePosition.call(this);
  32225. }
  32226. };
  32227. FreeCamera.prototype.dispose = function () {
  32228. this.inputs.clear();
  32229. _super.prototype.dispose.call(this);
  32230. };
  32231. FreeCamera.prototype.getClassName = function () {
  32232. return "FreeCamera";
  32233. };
  32234. return FreeCamera;
  32235. }(BABYLON.TargetCamera));
  32236. __decorate([
  32237. BABYLON.serializeAsVector3()
  32238. ], FreeCamera.prototype, "ellipsoid", void 0);
  32239. __decorate([
  32240. BABYLON.serialize()
  32241. ], FreeCamera.prototype, "checkCollisions", void 0);
  32242. __decorate([
  32243. BABYLON.serialize()
  32244. ], FreeCamera.prototype, "applyGravity", void 0);
  32245. BABYLON.FreeCamera = FreeCamera;
  32246. })(BABYLON || (BABYLON = {}));
  32247. //# sourceMappingURL=babylon.freeCamera.js.map
  32248. var BABYLON;
  32249. (function (BABYLON) {
  32250. var ArcRotateCameraKeyboardMoveInput = (function () {
  32251. function ArcRotateCameraKeyboardMoveInput() {
  32252. this._keys = [];
  32253. this.keysUp = [38];
  32254. this.keysDown = [40];
  32255. this.keysLeft = [37];
  32256. this.keysRight = [39];
  32257. }
  32258. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  32259. var _this = this;
  32260. element.tabIndex = 1;
  32261. this._onKeyDown = function (evt) {
  32262. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32263. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32264. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32265. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32266. var index = _this._keys.indexOf(evt.keyCode);
  32267. if (index === -1) {
  32268. _this._keys.push(evt.keyCode);
  32269. }
  32270. if (evt.preventDefault) {
  32271. if (!noPreventDefault) {
  32272. evt.preventDefault();
  32273. }
  32274. }
  32275. }
  32276. };
  32277. this._onKeyUp = function (evt) {
  32278. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32279. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32280. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32281. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32282. var index = _this._keys.indexOf(evt.keyCode);
  32283. if (index >= 0) {
  32284. _this._keys.splice(index, 1);
  32285. }
  32286. if (evt.preventDefault) {
  32287. if (!noPreventDefault) {
  32288. evt.preventDefault();
  32289. }
  32290. }
  32291. }
  32292. };
  32293. this._onLostFocus = function () {
  32294. _this._keys = [];
  32295. };
  32296. element.addEventListener("keydown", this._onKeyDown, false);
  32297. element.addEventListener("keyup", this._onKeyUp, false);
  32298. BABYLON.Tools.RegisterTopRootEvents([
  32299. { name: "blur", handler: this._onLostFocus }
  32300. ]);
  32301. };
  32302. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  32303. if (element) {
  32304. element.removeEventListener("keydown", this._onKeyDown);
  32305. element.removeEventListener("keyup", this._onKeyUp);
  32306. }
  32307. BABYLON.Tools.UnregisterTopRootEvents([
  32308. { name: "blur", handler: this._onLostFocus }
  32309. ]);
  32310. this._keys = [];
  32311. this._onKeyDown = null;
  32312. this._onKeyUp = null;
  32313. this._onLostFocus = null;
  32314. };
  32315. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  32316. if (this._onKeyDown) {
  32317. var camera = this.camera;
  32318. for (var index = 0; index < this._keys.length; index++) {
  32319. var keyCode = this._keys[index];
  32320. if (this.keysLeft.indexOf(keyCode) !== -1) {
  32321. camera.inertialAlphaOffset -= 0.01;
  32322. }
  32323. else if (this.keysUp.indexOf(keyCode) !== -1) {
  32324. camera.inertialBetaOffset -= 0.01;
  32325. }
  32326. else if (this.keysRight.indexOf(keyCode) !== -1) {
  32327. camera.inertialAlphaOffset += 0.01;
  32328. }
  32329. else if (this.keysDown.indexOf(keyCode) !== -1) {
  32330. camera.inertialBetaOffset += 0.01;
  32331. }
  32332. }
  32333. }
  32334. };
  32335. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  32336. return "ArcRotateCameraKeyboardMoveInput";
  32337. };
  32338. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  32339. return "keyboard";
  32340. };
  32341. return ArcRotateCameraKeyboardMoveInput;
  32342. }());
  32343. __decorate([
  32344. BABYLON.serialize()
  32345. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  32346. __decorate([
  32347. BABYLON.serialize()
  32348. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32349. __decorate([
  32350. BABYLON.serialize()
  32351. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32352. __decorate([
  32353. BABYLON.serialize()
  32354. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32355. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  32356. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  32357. })(BABYLON || (BABYLON = {}));
  32358. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  32359. var BABYLON;
  32360. (function (BABYLON) {
  32361. var ArcRotateCameraMouseWheelInput = (function () {
  32362. function ArcRotateCameraMouseWheelInput() {
  32363. this.wheelPrecision = 3.0;
  32364. }
  32365. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  32366. var _this = this;
  32367. this._wheel = function (p, s) {
  32368. //sanity check - this should be a PointerWheel event.
  32369. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  32370. return;
  32371. var event = p.event;
  32372. var delta = 0;
  32373. if (event.wheelDelta) {
  32374. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  32375. }
  32376. else if (event.detail) {
  32377. delta = -event.detail / _this.wheelPrecision;
  32378. }
  32379. if (delta)
  32380. _this.camera.inertialRadiusOffset += delta;
  32381. if (event.preventDefault) {
  32382. if (!noPreventDefault) {
  32383. event.preventDefault();
  32384. }
  32385. }
  32386. };
  32387. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  32388. };
  32389. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  32390. if (this._observer && element) {
  32391. this.camera.getScene().onPointerObservable.remove(this._observer);
  32392. this._observer = null;
  32393. this._wheel = null;
  32394. }
  32395. };
  32396. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  32397. return "ArcRotateCameraMouseWheelInput";
  32398. };
  32399. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  32400. return "mousewheel";
  32401. };
  32402. return ArcRotateCameraMouseWheelInput;
  32403. }());
  32404. __decorate([
  32405. BABYLON.serialize()
  32406. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  32407. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  32408. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  32409. })(BABYLON || (BABYLON = {}));
  32410. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  32411. var BABYLON;
  32412. (function (BABYLON) {
  32413. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  32414. var ArcRotateCameraPointersInput = (function () {
  32415. function ArcRotateCameraPointersInput() {
  32416. this.buttons = [0, 1, 2];
  32417. this.angularSensibilityX = 1000.0;
  32418. this.angularSensibilityY = 1000.0;
  32419. this.pinchPrecision = 6.0;
  32420. this.panningSensibility = 50.0;
  32421. this._isPanClick = false;
  32422. this.pinchInwards = true;
  32423. }
  32424. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  32425. var _this = this;
  32426. var engine = this.camera.getEngine();
  32427. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  32428. var pointA, pointB;
  32429. var previousPinchDistance = 0;
  32430. this._pointerInput = function (p, s) {
  32431. var evt = p.event;
  32432. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  32433. return;
  32434. }
  32435. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  32436. try {
  32437. evt.srcElement.setPointerCapture(evt.pointerId);
  32438. }
  32439. catch (e) {
  32440. //Nothing to do with the error. Execution will continue.
  32441. }
  32442. // Manage panning with pan button click
  32443. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  32444. // manage pointers
  32445. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  32446. if (pointA === undefined) {
  32447. pointA = cacheSoloPointer;
  32448. }
  32449. else if (pointB === undefined) {
  32450. pointB = cacheSoloPointer;
  32451. }
  32452. if (!noPreventDefault) {
  32453. evt.preventDefault();
  32454. element.focus();
  32455. }
  32456. }
  32457. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  32458. try {
  32459. evt.srcElement.releasePointerCapture(evt.pointerId);
  32460. }
  32461. catch (e) {
  32462. //Nothing to do with the error.
  32463. }
  32464. cacheSoloPointer = null;
  32465. previousPinchDistance = 0;
  32466. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  32467. //but emptying completly pointers collection is required to fix a bug on iPhone :
  32468. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  32469. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  32470. pointA = pointB = undefined;
  32471. if (!noPreventDefault) {
  32472. evt.preventDefault();
  32473. }
  32474. }
  32475. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32476. if (!noPreventDefault) {
  32477. evt.preventDefault();
  32478. }
  32479. // One button down
  32480. if (pointA && pointB === undefined) {
  32481. if (_this.panningSensibility !== 0 &&
  32482. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  32483. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  32484. _this.camera
  32485. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  32486. _this.camera
  32487. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  32488. }
  32489. else {
  32490. var offsetX = evt.clientX - cacheSoloPointer.x;
  32491. var offsetY = evt.clientY - cacheSoloPointer.y;
  32492. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32493. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32494. }
  32495. cacheSoloPointer.x = evt.clientX;
  32496. cacheSoloPointer.y = evt.clientY;
  32497. }
  32498. else if (pointA && pointB) {
  32499. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  32500. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  32501. ed.x = evt.clientX;
  32502. ed.y = evt.clientY;
  32503. var direction = _this.pinchInwards ? 1 : -1;
  32504. var distX = pointA.x - pointB.x;
  32505. var distY = pointA.y - pointB.y;
  32506. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  32507. if (previousPinchDistance === 0) {
  32508. previousPinchDistance = pinchSquaredDistance;
  32509. return;
  32510. }
  32511. if (pinchSquaredDistance !== previousPinchDistance) {
  32512. _this.camera
  32513. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  32514. (_this.pinchPrecision *
  32515. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  32516. direction);
  32517. previousPinchDistance = pinchSquaredDistance;
  32518. }
  32519. }
  32520. }
  32521. };
  32522. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  32523. this._onContextMenu = function (evt) {
  32524. evt.preventDefault();
  32525. };
  32526. if (!this.camera._useCtrlForPanning) {
  32527. element.addEventListener("contextmenu", this._onContextMenu, false);
  32528. }
  32529. this._onLostFocus = function () {
  32530. //this._keys = [];
  32531. pointA = pointB = undefined;
  32532. previousPinchDistance = 0;
  32533. cacheSoloPointer = null;
  32534. };
  32535. this._onMouseMove = function (evt) {
  32536. if (!engine.isPointerLock) {
  32537. return;
  32538. }
  32539. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32540. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32541. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32542. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32543. if (!noPreventDefault) {
  32544. evt.preventDefault();
  32545. }
  32546. };
  32547. this._onGestureStart = function (e) {
  32548. if (window.MSGesture === undefined) {
  32549. return;
  32550. }
  32551. if (!_this._MSGestureHandler) {
  32552. _this._MSGestureHandler = new MSGesture();
  32553. _this._MSGestureHandler.target = element;
  32554. }
  32555. _this._MSGestureHandler.addPointer(e.pointerId);
  32556. };
  32557. this._onGesture = function (e) {
  32558. _this.camera.radius *= e.scale;
  32559. if (e.preventDefault) {
  32560. if (!noPreventDefault) {
  32561. e.stopPropagation();
  32562. e.preventDefault();
  32563. }
  32564. }
  32565. };
  32566. element.addEventListener("mousemove", this._onMouseMove, false);
  32567. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  32568. element.addEventListener("MSGestureChange", this._onGesture, false);
  32569. BABYLON.Tools.RegisterTopRootEvents([
  32570. { name: "blur", handler: this._onLostFocus }
  32571. ]);
  32572. };
  32573. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  32574. if (element && this._observer) {
  32575. this.camera.getScene().onPointerObservable.remove(this._observer);
  32576. this._observer = null;
  32577. element.removeEventListener("contextmenu", this._onContextMenu);
  32578. element.removeEventListener("mousemove", this._onMouseMove);
  32579. element.removeEventListener("MSPointerDown", this._onGestureStart);
  32580. element.removeEventListener("MSGestureChange", this._onGesture);
  32581. this._isPanClick = false;
  32582. this.pinchInwards = true;
  32583. this._onMouseMove = null;
  32584. this._onGestureStart = null;
  32585. this._onGesture = null;
  32586. this._MSGestureHandler = null;
  32587. this._onLostFocus = null;
  32588. this._onContextMenu = null;
  32589. }
  32590. BABYLON.Tools.UnregisterTopRootEvents([
  32591. { name: "blur", handler: this._onLostFocus }
  32592. ]);
  32593. };
  32594. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  32595. return "ArcRotateCameraPointersInput";
  32596. };
  32597. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  32598. return "pointers";
  32599. };
  32600. return ArcRotateCameraPointersInput;
  32601. }());
  32602. __decorate([
  32603. BABYLON.serialize()
  32604. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  32605. __decorate([
  32606. BABYLON.serialize()
  32607. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  32608. __decorate([
  32609. BABYLON.serialize()
  32610. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  32611. __decorate([
  32612. BABYLON.serialize()
  32613. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  32614. __decorate([
  32615. BABYLON.serialize()
  32616. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  32617. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  32618. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  32619. })(BABYLON || (BABYLON = {}));
  32620. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  32621. /// <reference path="babylon.targetCamera.ts" />
  32622. /// <reference path="..\Tools\babylon.tools.ts" />
  32623. var BABYLON;
  32624. (function (BABYLON) {
  32625. var ArcRotateCamera = (function (_super) {
  32626. __extends(ArcRotateCamera, _super);
  32627. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  32628. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  32629. _this.inertialAlphaOffset = 0;
  32630. _this.inertialBetaOffset = 0;
  32631. _this.inertialRadiusOffset = 0;
  32632. _this.lowerAlphaLimit = null;
  32633. _this.upperAlphaLimit = null;
  32634. _this.lowerBetaLimit = 0.01;
  32635. _this.upperBetaLimit = Math.PI;
  32636. _this.lowerRadiusLimit = null;
  32637. _this.upperRadiusLimit = null;
  32638. _this.inertialPanningX = 0;
  32639. _this.inertialPanningY = 0;
  32640. _this.panningInertia = 0.9;
  32641. //-- end properties for backward compatibility for inputs
  32642. _this.zoomOnFactor = 1;
  32643. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  32644. _this.allowUpsideDown = true;
  32645. _this._viewMatrix = new BABYLON.Matrix();
  32646. // Panning
  32647. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  32648. _this.checkCollisions = false;
  32649. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32650. _this._previousPosition = BABYLON.Vector3.Zero();
  32651. _this._collisionVelocity = BABYLON.Vector3.Zero();
  32652. _this._newPosition = BABYLON.Vector3.Zero();
  32653. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32654. if (collidedMesh === void 0) { collidedMesh = null; }
  32655. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  32656. newPosition.multiplyInPlace(_this._collider.radius);
  32657. }
  32658. if (!collidedMesh) {
  32659. _this._previousPosition.copyFrom(_this.position);
  32660. }
  32661. else {
  32662. _this.setPosition(newPosition);
  32663. if (_this.onCollide) {
  32664. _this.onCollide(collidedMesh);
  32665. }
  32666. }
  32667. // Recompute because of constraints
  32668. var cosa = Math.cos(_this.alpha);
  32669. var sina = Math.sin(_this.alpha);
  32670. var cosb = Math.cos(_this.beta);
  32671. var sinb = Math.sin(_this.beta);
  32672. if (sinb === 0) {
  32673. sinb = 0.0001;
  32674. }
  32675. var target = _this._getTargetPosition();
  32676. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  32677. _this.position.copyFrom(_this._newPosition);
  32678. var up = _this.upVector;
  32679. if (_this.allowUpsideDown && _this.beta < 0) {
  32680. up = up.clone();
  32681. up = up.negate();
  32682. }
  32683. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  32684. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  32685. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  32686. _this._collisionTriggered = false;
  32687. };
  32688. _this._target = BABYLON.Vector3.Zero();
  32689. if (target) {
  32690. _this.setTarget(target);
  32691. }
  32692. _this.alpha = alpha;
  32693. _this.beta = beta;
  32694. _this.radius = radius;
  32695. _this.getViewMatrix();
  32696. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  32697. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  32698. return _this;
  32699. }
  32700. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  32701. get: function () {
  32702. return this._target;
  32703. },
  32704. set: function (value) {
  32705. this.setTarget(value);
  32706. },
  32707. enumerable: true,
  32708. configurable: true
  32709. });
  32710. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  32711. //-- begin properties for backward compatibility for inputs
  32712. get: function () {
  32713. var pointers = this.inputs.attached["pointers"];
  32714. if (pointers)
  32715. return pointers.angularSensibilityX;
  32716. },
  32717. set: function (value) {
  32718. var pointers = this.inputs.attached["pointers"];
  32719. if (pointers) {
  32720. pointers.angularSensibilityX = value;
  32721. }
  32722. },
  32723. enumerable: true,
  32724. configurable: true
  32725. });
  32726. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  32727. get: function () {
  32728. var pointers = this.inputs.attached["pointers"];
  32729. if (pointers)
  32730. return pointers.angularSensibilityY;
  32731. },
  32732. set: function (value) {
  32733. var pointers = this.inputs.attached["pointers"];
  32734. if (pointers) {
  32735. pointers.angularSensibilityY = value;
  32736. }
  32737. },
  32738. enumerable: true,
  32739. configurable: true
  32740. });
  32741. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  32742. get: function () {
  32743. var pointers = this.inputs.attached["pointers"];
  32744. if (pointers)
  32745. return pointers.pinchPrecision;
  32746. },
  32747. set: function (value) {
  32748. var pointers = this.inputs.attached["pointers"];
  32749. if (pointers) {
  32750. pointers.pinchPrecision = value;
  32751. }
  32752. },
  32753. enumerable: true,
  32754. configurable: true
  32755. });
  32756. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  32757. get: function () {
  32758. var pointers = this.inputs.attached["pointers"];
  32759. if (pointers)
  32760. return pointers.panningSensibility;
  32761. },
  32762. set: function (value) {
  32763. var pointers = this.inputs.attached["pointers"];
  32764. if (pointers) {
  32765. pointers.panningSensibility = value;
  32766. }
  32767. },
  32768. enumerable: true,
  32769. configurable: true
  32770. });
  32771. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  32772. get: function () {
  32773. var keyboard = this.inputs.attached["keyboard"];
  32774. if (keyboard)
  32775. return keyboard.keysUp;
  32776. },
  32777. set: function (value) {
  32778. var keyboard = this.inputs.attached["keyboard"];
  32779. if (keyboard)
  32780. keyboard.keysUp = value;
  32781. },
  32782. enumerable: true,
  32783. configurable: true
  32784. });
  32785. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  32786. get: function () {
  32787. var keyboard = this.inputs.attached["keyboard"];
  32788. if (keyboard)
  32789. return keyboard.keysDown;
  32790. },
  32791. set: function (value) {
  32792. var keyboard = this.inputs.attached["keyboard"];
  32793. if (keyboard)
  32794. keyboard.keysDown = value;
  32795. },
  32796. enumerable: true,
  32797. configurable: true
  32798. });
  32799. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  32800. get: function () {
  32801. var keyboard = this.inputs.attached["keyboard"];
  32802. if (keyboard)
  32803. return keyboard.keysLeft;
  32804. },
  32805. set: function (value) {
  32806. var keyboard = this.inputs.attached["keyboard"];
  32807. if (keyboard)
  32808. keyboard.keysLeft = value;
  32809. },
  32810. enumerable: true,
  32811. configurable: true
  32812. });
  32813. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  32814. get: function () {
  32815. var keyboard = this.inputs.attached["keyboard"];
  32816. if (keyboard)
  32817. return keyboard.keysRight;
  32818. },
  32819. set: function (value) {
  32820. var keyboard = this.inputs.attached["keyboard"];
  32821. if (keyboard)
  32822. keyboard.keysRight = value;
  32823. },
  32824. enumerable: true,
  32825. configurable: true
  32826. });
  32827. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  32828. get: function () {
  32829. var mousewheel = this.inputs.attached["mousewheel"];
  32830. if (mousewheel)
  32831. return mousewheel.wheelPrecision;
  32832. },
  32833. set: function (value) {
  32834. var mousewheel = this.inputs.attached["mousewheel"];
  32835. if (mousewheel)
  32836. mousewheel.wheelPrecision = value;
  32837. },
  32838. enumerable: true,
  32839. configurable: true
  32840. });
  32841. // Cache
  32842. ArcRotateCamera.prototype._initCache = function () {
  32843. _super.prototype._initCache.call(this);
  32844. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32845. this._cache.alpha = undefined;
  32846. this._cache.beta = undefined;
  32847. this._cache.radius = undefined;
  32848. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  32849. };
  32850. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  32851. if (!ignoreParentClass) {
  32852. _super.prototype._updateCache.call(this);
  32853. }
  32854. this._cache._target.copyFrom(this._getTargetPosition());
  32855. this._cache.alpha = this.alpha;
  32856. this._cache.beta = this.beta;
  32857. this._cache.radius = this.radius;
  32858. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  32859. };
  32860. ArcRotateCamera.prototype._getTargetPosition = function () {
  32861. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  32862. var pos = this._targetHost.getAbsolutePosition();
  32863. if (this._targetBoundingCenter) {
  32864. pos.addToRef(this._targetBoundingCenter, this._target);
  32865. }
  32866. else {
  32867. this._target.copyFrom(pos);
  32868. }
  32869. }
  32870. return this._target;
  32871. };
  32872. // Synchronized
  32873. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  32874. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  32875. return false;
  32876. return this._cache._target.equals(this._getTargetPosition())
  32877. && this._cache.alpha === this.alpha
  32878. && this._cache.beta === this.beta
  32879. && this._cache.radius === this.radius
  32880. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32881. };
  32882. // Methods
  32883. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32884. var _this = this;
  32885. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32886. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32887. this._useCtrlForPanning = useCtrlForPanning;
  32888. this._panningMouseButton = panningMouseButton;
  32889. this.inputs.attachElement(element, noPreventDefault);
  32890. this._reset = function () {
  32891. _this.inertialAlphaOffset = 0;
  32892. _this.inertialBetaOffset = 0;
  32893. _this.inertialRadiusOffset = 0;
  32894. };
  32895. };
  32896. ArcRotateCamera.prototype.detachControl = function (element) {
  32897. this.inputs.detachElement(element);
  32898. if (this._reset) {
  32899. this._reset();
  32900. }
  32901. };
  32902. ArcRotateCamera.prototype._checkInputs = function () {
  32903. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32904. if (this._collisionTriggered) {
  32905. return;
  32906. }
  32907. this.inputs.checkInputs();
  32908. // Inertia
  32909. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32910. if (this.getScene().useRightHandedSystem) {
  32911. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32912. }
  32913. else {
  32914. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32915. }
  32916. this.beta += this.inertialBetaOffset;
  32917. this.radius -= this.inertialRadiusOffset;
  32918. this.inertialAlphaOffset *= this.inertia;
  32919. this.inertialBetaOffset *= this.inertia;
  32920. this.inertialRadiusOffset *= this.inertia;
  32921. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  32922. this.inertialAlphaOffset = 0;
  32923. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  32924. this.inertialBetaOffset = 0;
  32925. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32926. this.inertialRadiusOffset = 0;
  32927. }
  32928. // Panning inertia
  32929. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32930. if (!this._localDirection) {
  32931. this._localDirection = BABYLON.Vector3.Zero();
  32932. this._transformedDirection = BABYLON.Vector3.Zero();
  32933. }
  32934. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32935. this._localDirection.multiplyInPlace(this.panningAxis);
  32936. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32937. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32938. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32939. if (!this.panningAxis.y) {
  32940. this._transformedDirection.y = 0;
  32941. }
  32942. if (!this._targetHost) {
  32943. this._target.addInPlace(this._transformedDirection);
  32944. }
  32945. this.inertialPanningX *= this.panningInertia;
  32946. this.inertialPanningY *= this.panningInertia;
  32947. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32948. this.inertialPanningX = 0;
  32949. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32950. this.inertialPanningY = 0;
  32951. }
  32952. // Limits
  32953. this._checkLimits();
  32954. _super.prototype._checkInputs.call(this);
  32955. };
  32956. ArcRotateCamera.prototype._checkLimits = function () {
  32957. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32958. if (this.allowUpsideDown && this.beta > Math.PI) {
  32959. this.beta = this.beta - (2 * Math.PI);
  32960. }
  32961. }
  32962. else {
  32963. if (this.beta < this.lowerBetaLimit) {
  32964. this.beta = this.lowerBetaLimit;
  32965. }
  32966. }
  32967. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32968. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32969. this.beta = this.beta + (2 * Math.PI);
  32970. }
  32971. }
  32972. else {
  32973. if (this.beta > this.upperBetaLimit) {
  32974. this.beta = this.upperBetaLimit;
  32975. }
  32976. }
  32977. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32978. this.alpha = this.lowerAlphaLimit;
  32979. }
  32980. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32981. this.alpha = this.upperAlphaLimit;
  32982. }
  32983. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32984. this.radius = this.lowerRadiusLimit;
  32985. }
  32986. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32987. this.radius = this.upperRadiusLimit;
  32988. }
  32989. };
  32990. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32991. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32992. this.radius = radiusv3.length();
  32993. // Alpha
  32994. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32995. if (radiusv3.z < 0) {
  32996. this.alpha = 2 * Math.PI - this.alpha;
  32997. }
  32998. // Beta
  32999. this.beta = Math.acos(radiusv3.y / this.radius);
  33000. this._checkLimits();
  33001. };
  33002. ArcRotateCamera.prototype.setPosition = function (position) {
  33003. if (this.position.equals(position)) {
  33004. return;
  33005. }
  33006. this.position.copyFrom(position);
  33007. this.rebuildAnglesAndRadius();
  33008. };
  33009. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  33010. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  33011. if (allowSamePosition === void 0) { allowSamePosition = false; }
  33012. if (target.getBoundingInfo) {
  33013. if (toBoundingCenter) {
  33014. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  33015. }
  33016. else {
  33017. this._targetBoundingCenter = null;
  33018. }
  33019. this._targetHost = target;
  33020. this._target = this._getTargetPosition();
  33021. }
  33022. else {
  33023. var newTarget = target;
  33024. var currentTarget = this._getTargetPosition();
  33025. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  33026. return;
  33027. }
  33028. this._target = newTarget;
  33029. this._targetBoundingCenter = null;
  33030. }
  33031. this.rebuildAnglesAndRadius();
  33032. };
  33033. ArcRotateCamera.prototype._getViewMatrix = function () {
  33034. // Compute
  33035. var cosa = Math.cos(this.alpha);
  33036. var sina = Math.sin(this.alpha);
  33037. var cosb = Math.cos(this.beta);
  33038. var sinb = Math.sin(this.beta);
  33039. if (sinb === 0) {
  33040. sinb = 0.0001;
  33041. }
  33042. var target = this._getTargetPosition();
  33043. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  33044. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  33045. if (!this._collider) {
  33046. this._collider = new BABYLON.Collider();
  33047. }
  33048. this._collider.radius = this.collisionRadius;
  33049. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  33050. this._collisionTriggered = true;
  33051. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  33052. }
  33053. else {
  33054. this.position.copyFrom(this._newPosition);
  33055. var up = this.upVector;
  33056. if (this.allowUpsideDown && sinb < 0) {
  33057. up = up.clone();
  33058. up = up.negate();
  33059. }
  33060. if (this.getScene().useRightHandedSystem) {
  33061. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  33062. }
  33063. else {
  33064. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  33065. }
  33066. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  33067. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  33068. }
  33069. this._currentTarget = target;
  33070. return this._viewMatrix;
  33071. };
  33072. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  33073. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  33074. meshes = meshes || this.getScene().meshes;
  33075. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  33076. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  33077. this.radius = distance * this.zoomOnFactor;
  33078. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  33079. };
  33080. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  33081. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  33082. var meshesOrMinMaxVector;
  33083. var distance;
  33084. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  33085. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  33086. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  33087. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  33088. }
  33089. else {
  33090. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  33091. distance = meshesOrMinMaxVectorAndDistance.distance;
  33092. }
  33093. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  33094. if (!doNotUpdateMaxZ) {
  33095. this.maxZ = distance * 2;
  33096. }
  33097. };
  33098. /**
  33099. * @override
  33100. * Override Camera.createRigCamera
  33101. */
  33102. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  33103. var alphaShift;
  33104. switch (this.cameraRigMode) {
  33105. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33106. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33107. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33108. case BABYLON.Camera.RIG_MODE_VR:
  33109. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  33110. break;
  33111. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33112. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  33113. break;
  33114. }
  33115. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  33116. rigCam._cameraRigParams = {};
  33117. return rigCam;
  33118. };
  33119. /**
  33120. * @override
  33121. * Override Camera._updateRigCameras
  33122. */
  33123. ArcRotateCamera.prototype._updateRigCameras = function () {
  33124. var camLeft = this._rigCameras[0];
  33125. var camRight = this._rigCameras[1];
  33126. camLeft.beta = camRight.beta = this.beta;
  33127. camLeft.radius = camRight.radius = this.radius;
  33128. switch (this.cameraRigMode) {
  33129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33130. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33131. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33132. case BABYLON.Camera.RIG_MODE_VR:
  33133. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  33134. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  33135. break;
  33136. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33137. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  33138. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  33139. break;
  33140. }
  33141. _super.prototype._updateRigCameras.call(this);
  33142. };
  33143. ArcRotateCamera.prototype.dispose = function () {
  33144. this.inputs.clear();
  33145. _super.prototype.dispose.call(this);
  33146. };
  33147. ArcRotateCamera.prototype.getClassName = function () {
  33148. return "ArcRotateCamera";
  33149. };
  33150. return ArcRotateCamera;
  33151. }(BABYLON.TargetCamera));
  33152. __decorate([
  33153. BABYLON.serialize()
  33154. ], ArcRotateCamera.prototype, "alpha", void 0);
  33155. __decorate([
  33156. BABYLON.serialize()
  33157. ], ArcRotateCamera.prototype, "beta", void 0);
  33158. __decorate([
  33159. BABYLON.serialize()
  33160. ], ArcRotateCamera.prototype, "radius", void 0);
  33161. __decorate([
  33162. BABYLON.serializeAsVector3("target")
  33163. ], ArcRotateCamera.prototype, "_target", void 0);
  33164. __decorate([
  33165. BABYLON.serialize()
  33166. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  33167. __decorate([
  33168. BABYLON.serialize()
  33169. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  33170. __decorate([
  33171. BABYLON.serialize()
  33172. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  33173. __decorate([
  33174. BABYLON.serialize()
  33175. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  33176. __decorate([
  33177. BABYLON.serialize()
  33178. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  33179. __decorate([
  33180. BABYLON.serialize()
  33181. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  33182. __decorate([
  33183. BABYLON.serialize()
  33184. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  33185. __decorate([
  33186. BABYLON.serialize()
  33187. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  33188. __decorate([
  33189. BABYLON.serialize()
  33190. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  33191. __decorate([
  33192. BABYLON.serialize()
  33193. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  33194. __decorate([
  33195. BABYLON.serialize()
  33196. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  33197. __decorate([
  33198. BABYLON.serialize()
  33199. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  33200. __decorate([
  33201. BABYLON.serialize()
  33202. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  33203. __decorate([
  33204. BABYLON.serialize()
  33205. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  33206. BABYLON.ArcRotateCamera = ArcRotateCamera;
  33207. })(BABYLON || (BABYLON = {}));
  33208. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  33209. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  33210. var BABYLON;
  33211. (function (BABYLON) {
  33212. var ArcRotateCameraInputsManager = (function (_super) {
  33213. __extends(ArcRotateCameraInputsManager, _super);
  33214. function ArcRotateCameraInputsManager(camera) {
  33215. return _super.call(this, camera) || this;
  33216. }
  33217. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  33218. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  33219. return this;
  33220. };
  33221. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  33222. this.add(new BABYLON.ArcRotateCameraPointersInput());
  33223. return this;
  33224. };
  33225. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  33226. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  33227. return this;
  33228. };
  33229. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  33230. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  33231. return this;
  33232. };
  33233. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  33234. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  33235. return this;
  33236. };
  33237. return ArcRotateCameraInputsManager;
  33238. }(BABYLON.CameraInputsManager));
  33239. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  33240. })(BABYLON || (BABYLON = {}));
  33241. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  33242. var BABYLON;
  33243. (function (BABYLON) {
  33244. var HemisphericLight = (function (_super) {
  33245. __extends(HemisphericLight, _super);
  33246. /**
  33247. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  33248. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  33249. * The HemisphericLight can't cast shadows.
  33250. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33251. */
  33252. function HemisphericLight(name, direction, scene) {
  33253. var _this = _super.call(this, name, scene) || this;
  33254. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  33255. _this.direction = direction || BABYLON.Vector3.Up();
  33256. return _this;
  33257. }
  33258. HemisphericLight.prototype._buildUniformLayout = function () {
  33259. this._uniformBuffer.addUniform("vLightData", 4);
  33260. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33261. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33262. this._uniformBuffer.addUniform("vLightGround", 3);
  33263. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33264. this._uniformBuffer.create();
  33265. };
  33266. /**
  33267. * Returns the string "HemisphericLight".
  33268. */
  33269. HemisphericLight.prototype.getClassName = function () {
  33270. return "HemisphericLight";
  33271. };
  33272. /**
  33273. * Sets the HemisphericLight direction towards the passed target (Vector3).
  33274. * Returns the updated direction.
  33275. */
  33276. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  33277. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  33278. return this.direction;
  33279. };
  33280. HemisphericLight.prototype.getShadowGenerator = function () {
  33281. return null;
  33282. };
  33283. /**
  33284. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  33285. * Returns the HemisphericLight.
  33286. */
  33287. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  33288. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  33289. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  33290. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  33291. return this;
  33292. };
  33293. HemisphericLight.prototype._getWorldMatrix = function () {
  33294. if (!this._worldMatrix) {
  33295. this._worldMatrix = BABYLON.Matrix.Identity();
  33296. }
  33297. return this._worldMatrix;
  33298. };
  33299. /**
  33300. * Returns the integer 3.
  33301. */
  33302. HemisphericLight.prototype.getTypeID = function () {
  33303. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  33304. };
  33305. return HemisphericLight;
  33306. }(BABYLON.Light));
  33307. __decorate([
  33308. BABYLON.serializeAsColor3()
  33309. ], HemisphericLight.prototype, "groundColor", void 0);
  33310. __decorate([
  33311. BABYLON.serializeAsVector3()
  33312. ], HemisphericLight.prototype, "direction", void 0);
  33313. BABYLON.HemisphericLight = HemisphericLight;
  33314. })(BABYLON || (BABYLON = {}));
  33315. //# sourceMappingURL=babylon.hemisphericLight.js.map
  33316. var BABYLON;
  33317. (function (BABYLON) {
  33318. var ShadowLight = (function (_super) {
  33319. __extends(ShadowLight, _super);
  33320. function ShadowLight() {
  33321. var _this = _super !== null && _super.apply(this, arguments) || this;
  33322. _this._needProjectionMatrixCompute = true;
  33323. return _this;
  33324. }
  33325. Object.defineProperty(ShadowLight.prototype, "direction", {
  33326. get: function () {
  33327. return this._direction;
  33328. },
  33329. set: function (value) {
  33330. this._direction = value;
  33331. },
  33332. enumerable: true,
  33333. configurable: true
  33334. });
  33335. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  33336. get: function () {
  33337. return this._shadowMinZ;
  33338. },
  33339. set: function (value) {
  33340. this._shadowMinZ = value;
  33341. this.forceProjectionMatrixCompute();
  33342. },
  33343. enumerable: true,
  33344. configurable: true
  33345. });
  33346. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  33347. get: function () {
  33348. return this._shadowMaxZ;
  33349. },
  33350. set: function (value) {
  33351. this._shadowMaxZ = value;
  33352. this.forceProjectionMatrixCompute();
  33353. },
  33354. enumerable: true,
  33355. configurable: true
  33356. });
  33357. /**
  33358. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  33359. */
  33360. ShadowLight.prototype.computeTransformedInformation = function () {
  33361. if (this.parent && this.parent.getWorldMatrix) {
  33362. if (!this.transformedPosition) {
  33363. this.transformedPosition = BABYLON.Vector3.Zero();
  33364. }
  33365. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  33366. // In case the direction is present.
  33367. if (this.direction) {
  33368. if (!this.transformedDirection) {
  33369. this.transformedDirection = BABYLON.Vector3.Zero();
  33370. }
  33371. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  33372. }
  33373. return true;
  33374. }
  33375. return false;
  33376. };
  33377. /**
  33378. * Return the depth scale used for the shadow map.
  33379. */
  33380. ShadowLight.prototype.getDepthScale = function () {
  33381. return 30.0;
  33382. };
  33383. /**
  33384. * Returns the light direction (Vector3) for any passed face index.
  33385. */
  33386. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  33387. return this.transformedDirection ? this.transformedDirection : this.direction;
  33388. };
  33389. /**
  33390. * Returns the DirectionalLight absolute position in the World.
  33391. */
  33392. ShadowLight.prototype.getAbsolutePosition = function () {
  33393. return this.transformedPosition ? this.transformedPosition : this.position;
  33394. };
  33395. /**
  33396. * Sets the DirectionalLight direction toward the passed target (Vector3).
  33397. * Returns the updated DirectionalLight direction (Vector3).
  33398. */
  33399. ShadowLight.prototype.setDirectionToTarget = function (target) {
  33400. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  33401. return this.direction;
  33402. };
  33403. /**
  33404. * Returns the light rotation (Vector3).
  33405. */
  33406. ShadowLight.prototype.getRotation = function () {
  33407. this.direction.normalize();
  33408. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  33409. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  33410. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  33411. };
  33412. /**
  33413. * Boolean : false by default.
  33414. */
  33415. ShadowLight.prototype.needCube = function () {
  33416. return false;
  33417. };
  33418. /**
  33419. * Specifies wether or not the projection matrix should be recomputed this frame.
  33420. */
  33421. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  33422. return this._needProjectionMatrixCompute;
  33423. };
  33424. /**
  33425. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  33426. */
  33427. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  33428. this._needProjectionMatrixCompute = true;
  33429. };
  33430. /**
  33431. * Get the world matrix of the sahdow lights.
  33432. */
  33433. ShadowLight.prototype._getWorldMatrix = function () {
  33434. if (!this._worldMatrix) {
  33435. this._worldMatrix = BABYLON.Matrix.Identity();
  33436. }
  33437. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  33438. return this._worldMatrix;
  33439. };
  33440. /**
  33441. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  33442. * Returns the light.
  33443. */
  33444. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33445. if (this.customProjectionMatrixBuilder) {
  33446. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  33447. }
  33448. else {
  33449. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  33450. }
  33451. return this;
  33452. };
  33453. return ShadowLight;
  33454. }(BABYLON.Light));
  33455. __decorate([
  33456. BABYLON.serializeAsVector3()
  33457. ], ShadowLight.prototype, "position", void 0);
  33458. __decorate([
  33459. BABYLON.serializeAsVector3()
  33460. ], ShadowLight.prototype, "direction", null);
  33461. __decorate([
  33462. BABYLON.serialize()
  33463. ], ShadowLight.prototype, "shadowMinZ", null);
  33464. __decorate([
  33465. BABYLON.serialize()
  33466. ], ShadowLight.prototype, "shadowMaxZ", null);
  33467. BABYLON.ShadowLight = ShadowLight;
  33468. })(BABYLON || (BABYLON = {}));
  33469. //# sourceMappingURL=babylon.shadowLight.js.map
  33470. var BABYLON;
  33471. (function (BABYLON) {
  33472. var PointLight = (function (_super) {
  33473. __extends(PointLight, _super);
  33474. /**
  33475. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  33476. * A PointLight emits the light in every direction.
  33477. * It can cast shadows.
  33478. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  33479. * ```javascript
  33480. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  33481. * ```
  33482. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33483. */
  33484. function PointLight(name, position, scene) {
  33485. var _this = _super.call(this, name, scene) || this;
  33486. _this._shadowAngle = Math.PI / 2;
  33487. _this.position = position;
  33488. return _this;
  33489. }
  33490. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  33491. /**
  33492. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33493. * This specifies what angle the shadow will use to be created.
  33494. *
  33495. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33496. */
  33497. get: function () {
  33498. return this._shadowAngle;
  33499. },
  33500. /**
  33501. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33502. * This specifies what angle the shadow will use to be created.
  33503. *
  33504. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33505. */
  33506. set: function (value) {
  33507. this._shadowAngle = value;
  33508. this.forceProjectionMatrixCompute();
  33509. },
  33510. enumerable: true,
  33511. configurable: true
  33512. });
  33513. Object.defineProperty(PointLight.prototype, "direction", {
  33514. get: function () {
  33515. return this._direction;
  33516. },
  33517. /**
  33518. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33519. */
  33520. set: function (value) {
  33521. var previousNeedCube = this.needCube();
  33522. this._direction = value;
  33523. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  33524. this._shadowGenerator.recreateShadowMap();
  33525. }
  33526. },
  33527. enumerable: true,
  33528. configurable: true
  33529. });
  33530. /**
  33531. * Returns the string "PointLight"
  33532. */
  33533. PointLight.prototype.getClassName = function () {
  33534. return "PointLight";
  33535. };
  33536. /**
  33537. * Returns the integer 0.
  33538. */
  33539. PointLight.prototype.getTypeID = function () {
  33540. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  33541. };
  33542. /**
  33543. * Specifies wether or not the shadowmap should be a cube texture.
  33544. */
  33545. PointLight.prototype.needCube = function () {
  33546. return !this.direction;
  33547. };
  33548. /**
  33549. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  33550. */
  33551. PointLight.prototype.getShadowDirection = function (faceIndex) {
  33552. if (this.direction) {
  33553. return _super.prototype.getShadowDirection.call(this, faceIndex);
  33554. }
  33555. else {
  33556. switch (faceIndex) {
  33557. case 0:
  33558. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  33559. case 1:
  33560. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  33561. case 2:
  33562. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  33563. case 3:
  33564. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  33565. case 4:
  33566. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  33567. case 5:
  33568. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  33569. }
  33570. }
  33571. return BABYLON.Vector3.Zero();
  33572. };
  33573. /**
  33574. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  33575. * - fov = PI / 2
  33576. * - aspect ratio : 1.0
  33577. * - z-near and far equal to the active camera minZ and maxZ.
  33578. * Returns the PointLight.
  33579. */
  33580. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33581. var activeCamera = this.getScene().activeCamera;
  33582. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  33583. };
  33584. PointLight.prototype._buildUniformLayout = function () {
  33585. this._uniformBuffer.addUniform("vLightData", 4);
  33586. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33587. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33588. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33589. this._uniformBuffer.create();
  33590. };
  33591. /**
  33592. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  33593. * Returns the PointLight.
  33594. */
  33595. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  33596. if (this.computeTransformedInformation()) {
  33597. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  33598. return this;
  33599. }
  33600. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  33601. return this;
  33602. };
  33603. return PointLight;
  33604. }(BABYLON.ShadowLight));
  33605. __decorate([
  33606. BABYLON.serialize()
  33607. ], PointLight.prototype, "shadowAngle", null);
  33608. BABYLON.PointLight = PointLight;
  33609. })(BABYLON || (BABYLON = {}));
  33610. //# sourceMappingURL=babylon.pointLight.js.map
  33611. /// <reference path="babylon.light.ts" />
  33612. var BABYLON;
  33613. (function (BABYLON) {
  33614. var DirectionalLight = (function (_super) {
  33615. __extends(DirectionalLight, _super);
  33616. /**
  33617. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  33618. * The directional light is emitted from everywhere in the given direction.
  33619. * It can cast shawdows.
  33620. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33621. */
  33622. function DirectionalLight(name, direction, scene) {
  33623. var _this = _super.call(this, name, scene) || this;
  33624. _this._shadowFrustumSize = 0;
  33625. _this._shadowOrthoScale = 0.5;
  33626. _this.autoUpdateExtends = true;
  33627. // Cache
  33628. _this._orthoLeft = Number.MAX_VALUE;
  33629. _this._orthoRight = Number.MIN_VALUE;
  33630. _this._orthoTop = Number.MIN_VALUE;
  33631. _this._orthoBottom = Number.MAX_VALUE;
  33632. _this.position = direction.scale(-1.0);
  33633. _this.direction = direction;
  33634. return _this;
  33635. }
  33636. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  33637. /**
  33638. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  33639. */
  33640. get: function () {
  33641. return this._shadowFrustumSize;
  33642. },
  33643. /**
  33644. * Specifies a fix frustum size for the shadow generation.
  33645. */
  33646. set: function (value) {
  33647. this._shadowFrustumSize = value;
  33648. this.forceProjectionMatrixCompute();
  33649. },
  33650. enumerable: true,
  33651. configurable: true
  33652. });
  33653. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  33654. get: function () {
  33655. return this._shadowOrthoScale;
  33656. },
  33657. set: function (value) {
  33658. this._shadowOrthoScale = value;
  33659. this.forceProjectionMatrixCompute();
  33660. },
  33661. enumerable: true,
  33662. configurable: true
  33663. });
  33664. /**
  33665. * Returns the string "DirectionalLight".
  33666. */
  33667. DirectionalLight.prototype.getClassName = function () {
  33668. return "DirectionalLight";
  33669. };
  33670. /**
  33671. * Returns the integer 1.
  33672. */
  33673. DirectionalLight.prototype.getTypeID = function () {
  33674. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  33675. };
  33676. /**
  33677. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  33678. * Returns the DirectionalLight Shadow projection matrix.
  33679. */
  33680. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33681. if (this.shadowFrustumSize > 0) {
  33682. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  33683. }
  33684. else {
  33685. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  33686. }
  33687. };
  33688. /**
  33689. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  33690. * Returns the DirectionalLight Shadow projection matrix.
  33691. */
  33692. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  33693. var activeCamera = this.getScene().activeCamera;
  33694. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  33695. };
  33696. /**
  33697. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  33698. * Returns the DirectionalLight Shadow projection matrix.
  33699. */
  33700. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33701. var activeCamera = this.getScene().activeCamera;
  33702. // Check extends
  33703. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  33704. var tempVector3 = BABYLON.Vector3.Zero();
  33705. this._orthoLeft = Number.MAX_VALUE;
  33706. this._orthoRight = Number.MIN_VALUE;
  33707. this._orthoTop = Number.MIN_VALUE;
  33708. this._orthoBottom = Number.MAX_VALUE;
  33709. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  33710. var mesh = renderList[meshIndex];
  33711. if (!mesh) {
  33712. continue;
  33713. }
  33714. var boundingInfo = mesh.getBoundingInfo();
  33715. if (!boundingInfo) {
  33716. continue;
  33717. }
  33718. var boundingBox = boundingInfo.boundingBox;
  33719. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  33720. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  33721. if (tempVector3.x < this._orthoLeft)
  33722. this._orthoLeft = tempVector3.x;
  33723. if (tempVector3.y < this._orthoBottom)
  33724. this._orthoBottom = tempVector3.y;
  33725. if (tempVector3.x > this._orthoRight)
  33726. this._orthoRight = tempVector3.x;
  33727. if (tempVector3.y > this._orthoTop)
  33728. this._orthoTop = tempVector3.y;
  33729. }
  33730. }
  33731. }
  33732. var xOffset = this._orthoRight - this._orthoLeft;
  33733. var yOffset = this._orthoTop - this._orthoBottom;
  33734. 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);
  33735. };
  33736. DirectionalLight.prototype._buildUniformLayout = function () {
  33737. this._uniformBuffer.addUniform("vLightData", 4);
  33738. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33739. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33740. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33741. this._uniformBuffer.create();
  33742. };
  33743. /**
  33744. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  33745. * Returns the DirectionalLight.
  33746. */
  33747. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  33748. if (this.computeTransformedInformation()) {
  33749. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  33750. return this;
  33751. }
  33752. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  33753. return this;
  33754. };
  33755. return DirectionalLight;
  33756. }(BABYLON.ShadowLight));
  33757. __decorate([
  33758. BABYLON.serialize()
  33759. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  33760. __decorate([
  33761. BABYLON.serialize()
  33762. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  33763. __decorate([
  33764. BABYLON.serialize()
  33765. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  33766. BABYLON.DirectionalLight = DirectionalLight;
  33767. })(BABYLON || (BABYLON = {}));
  33768. //# sourceMappingURL=babylon.directionalLight.js.map
  33769. var BABYLON;
  33770. (function (BABYLON) {
  33771. var SpotLight = (function (_super) {
  33772. __extends(SpotLight, _super);
  33773. /**
  33774. * Creates a SpotLight object in the scene with the passed parameters :
  33775. * - `position` (Vector3) is the initial SpotLight position,
  33776. * - `direction` (Vector3) is the initial SpotLight direction,
  33777. * - `angle` (float, in radians) is the spot light cone angle,
  33778. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  33779. * A spot light is a simply light oriented cone.
  33780. * It can cast shadows.
  33781. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33782. */
  33783. function SpotLight(name, position, direction, angle, exponent, scene) {
  33784. var _this = _super.call(this, name, scene) || this;
  33785. _this.position = position;
  33786. _this.direction = direction;
  33787. _this.angle = angle;
  33788. _this.exponent = exponent;
  33789. return _this;
  33790. }
  33791. Object.defineProperty(SpotLight.prototype, "angle", {
  33792. get: function () {
  33793. return this._angle;
  33794. },
  33795. set: function (value) {
  33796. this._angle = value;
  33797. this.forceProjectionMatrixCompute();
  33798. },
  33799. enumerable: true,
  33800. configurable: true
  33801. });
  33802. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  33803. get: function () {
  33804. return this._shadowAngleScale;
  33805. },
  33806. /**
  33807. * Allows scaling the angle of the light for shadow generation only.
  33808. */
  33809. set: function (value) {
  33810. this._shadowAngleScale = value;
  33811. this.forceProjectionMatrixCompute();
  33812. },
  33813. enumerable: true,
  33814. configurable: true
  33815. });
  33816. /**
  33817. * Returns the string "SpotLight".
  33818. */
  33819. SpotLight.prototype.getClassName = function () {
  33820. return "SpotLight";
  33821. };
  33822. /**
  33823. * Returns the integer 2.
  33824. */
  33825. SpotLight.prototype.getTypeID = function () {
  33826. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  33827. };
  33828. /**
  33829. * 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.
  33830. * Returns the SpotLight.
  33831. */
  33832. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33833. var activeCamera = this.getScene().activeCamera;
  33834. this._shadowAngleScale = this._shadowAngleScale || 1;
  33835. var angle = this._shadowAngleScale * this._angle;
  33836. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  33837. };
  33838. SpotLight.prototype._buildUniformLayout = function () {
  33839. this._uniformBuffer.addUniform("vLightData", 4);
  33840. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33841. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33842. this._uniformBuffer.addUniform("vLightDirection", 3);
  33843. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33844. this._uniformBuffer.create();
  33845. };
  33846. /**
  33847. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  33848. * Return the SpotLight.
  33849. */
  33850. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  33851. var normalizeDirection;
  33852. if (this.computeTransformedInformation()) {
  33853. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  33854. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  33855. }
  33856. else {
  33857. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  33858. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  33859. }
  33860. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  33861. return this;
  33862. };
  33863. return SpotLight;
  33864. }(BABYLON.ShadowLight));
  33865. __decorate([
  33866. BABYLON.serialize()
  33867. ], SpotLight.prototype, "angle", null);
  33868. __decorate([
  33869. BABYLON.serialize()
  33870. /**
  33871. * Allows scaling the angle of the light for shadow generation only.
  33872. */
  33873. ], SpotLight.prototype, "shadowAngleScale", null);
  33874. __decorate([
  33875. BABYLON.serialize()
  33876. ], SpotLight.prototype, "exponent", void 0);
  33877. BABYLON.SpotLight = SpotLight;
  33878. })(BABYLON || (BABYLON = {}));
  33879. //# sourceMappingURL=babylon.spotLight.js.map
  33880. var BABYLON;
  33881. (function (BABYLON) {
  33882. var AnimationRange = (function () {
  33883. function AnimationRange(name, from, to) {
  33884. this.name = name;
  33885. this.from = from;
  33886. this.to = to;
  33887. }
  33888. AnimationRange.prototype.clone = function () {
  33889. return new AnimationRange(this.name, this.from, this.to);
  33890. };
  33891. return AnimationRange;
  33892. }());
  33893. BABYLON.AnimationRange = AnimationRange;
  33894. /**
  33895. * Composed of a frame, and an action function
  33896. */
  33897. var AnimationEvent = (function () {
  33898. function AnimationEvent(frame, action, onlyOnce) {
  33899. this.frame = frame;
  33900. this.action = action;
  33901. this.onlyOnce = onlyOnce;
  33902. this.isDone = false;
  33903. }
  33904. return AnimationEvent;
  33905. }());
  33906. BABYLON.AnimationEvent = AnimationEvent;
  33907. var PathCursor = (function () {
  33908. function PathCursor(path) {
  33909. this.path = path;
  33910. this._onchange = new Array();
  33911. this.value = 0;
  33912. this.animations = new Array();
  33913. }
  33914. PathCursor.prototype.getPoint = function () {
  33915. var point = this.path.getPointAtLengthPosition(this.value);
  33916. return new BABYLON.Vector3(point.x, 0, point.y);
  33917. };
  33918. PathCursor.prototype.moveAhead = function (step) {
  33919. if (step === void 0) { step = 0.002; }
  33920. this.move(step);
  33921. return this;
  33922. };
  33923. PathCursor.prototype.moveBack = function (step) {
  33924. if (step === void 0) { step = 0.002; }
  33925. this.move(-step);
  33926. return this;
  33927. };
  33928. PathCursor.prototype.move = function (step) {
  33929. if (Math.abs(step) > 1) {
  33930. throw "step size should be less than 1.";
  33931. }
  33932. this.value += step;
  33933. this.ensureLimits();
  33934. this.raiseOnChange();
  33935. return this;
  33936. };
  33937. PathCursor.prototype.ensureLimits = function () {
  33938. while (this.value > 1) {
  33939. this.value -= 1;
  33940. }
  33941. while (this.value < 0) {
  33942. this.value += 1;
  33943. }
  33944. return this;
  33945. };
  33946. // used by animation engine
  33947. PathCursor.prototype.markAsDirty = function (propertyName) {
  33948. this.ensureLimits();
  33949. this.raiseOnChange();
  33950. return this;
  33951. };
  33952. PathCursor.prototype.raiseOnChange = function () {
  33953. var _this = this;
  33954. this._onchange.forEach(function (f) { return f(_this); });
  33955. return this;
  33956. };
  33957. PathCursor.prototype.onchange = function (f) {
  33958. this._onchange.push(f);
  33959. return this;
  33960. };
  33961. return PathCursor;
  33962. }());
  33963. BABYLON.PathCursor = PathCursor;
  33964. var Animation = (function () {
  33965. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  33966. this.name = name;
  33967. this.targetProperty = targetProperty;
  33968. this.framePerSecond = framePerSecond;
  33969. this.dataType = dataType;
  33970. this.loopMode = loopMode;
  33971. this.enableBlending = enableBlending;
  33972. this._offsetsCache = {};
  33973. this._highLimitsCache = {};
  33974. this._stopped = false;
  33975. this._blendingFactor = 0;
  33976. // The set of event that will be linked to this animation
  33977. this._events = new Array();
  33978. this.allowMatricesInterpolation = false;
  33979. this.blendingSpeed = 0.01;
  33980. this._ranges = {};
  33981. this.targetPropertyPath = targetProperty.split(".");
  33982. this.dataType = dataType;
  33983. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  33984. }
  33985. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  33986. var dataType = undefined;
  33987. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  33988. dataType = Animation.ANIMATIONTYPE_FLOAT;
  33989. }
  33990. else if (from instanceof BABYLON.Quaternion) {
  33991. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  33992. }
  33993. else if (from instanceof BABYLON.Vector3) {
  33994. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  33995. }
  33996. else if (from instanceof BABYLON.Vector2) {
  33997. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  33998. }
  33999. else if (from instanceof BABYLON.Color3) {
  34000. dataType = Animation.ANIMATIONTYPE_COLOR3;
  34001. }
  34002. else if (from instanceof BABYLON.Size) {
  34003. dataType = Animation.ANIMATIONTYPE_SIZE;
  34004. }
  34005. if (dataType == undefined) {
  34006. return null;
  34007. }
  34008. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  34009. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  34010. animation.setKeys(keys);
  34011. if (easingFunction !== undefined) {
  34012. animation.setEasingFunction(easingFunction);
  34013. }
  34014. return animation;
  34015. };
  34016. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34017. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34018. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34019. };
  34020. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34021. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34022. node.animations.push(animation);
  34023. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34024. };
  34025. // Methods
  34026. /**
  34027. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  34028. */
  34029. Animation.prototype.toString = function (fullDetails) {
  34030. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  34031. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  34032. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  34033. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  34034. if (fullDetails) {
  34035. ret += ", Ranges: {";
  34036. var first = true;
  34037. for (var name in this._ranges) {
  34038. if (first) {
  34039. ret += ", ";
  34040. first = false;
  34041. }
  34042. ret += name;
  34043. }
  34044. ret += "}";
  34045. }
  34046. return ret;
  34047. };
  34048. /**
  34049. * Add an event to this animation.
  34050. */
  34051. Animation.prototype.addEvent = function (event) {
  34052. this._events.push(event);
  34053. };
  34054. /**
  34055. * Remove all events found at the given frame
  34056. * @param frame
  34057. */
  34058. Animation.prototype.removeEvents = function (frame) {
  34059. for (var index = 0; index < this._events.length; index++) {
  34060. if (this._events[index].frame === frame) {
  34061. this._events.splice(index, 1);
  34062. index--;
  34063. }
  34064. }
  34065. };
  34066. Animation.prototype.createRange = function (name, from, to) {
  34067. // check name not already in use; could happen for bones after serialized
  34068. if (!this._ranges[name]) {
  34069. this._ranges[name] = new AnimationRange(name, from, to);
  34070. }
  34071. };
  34072. Animation.prototype.deleteRange = function (name, deleteFrames) {
  34073. if (deleteFrames === void 0) { deleteFrames = true; }
  34074. if (this._ranges[name]) {
  34075. if (deleteFrames) {
  34076. var from = this._ranges[name].from;
  34077. var to = this._ranges[name].to;
  34078. // this loop MUST go high to low for multiple splices to work
  34079. for (var key = this._keys.length - 1; key >= 0; key--) {
  34080. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  34081. this._keys.splice(key, 1);
  34082. }
  34083. }
  34084. }
  34085. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  34086. }
  34087. };
  34088. Animation.prototype.getRange = function (name) {
  34089. return this._ranges[name];
  34090. };
  34091. Animation.prototype.reset = function () {
  34092. this._offsetsCache = {};
  34093. this._highLimitsCache = {};
  34094. this.currentFrame = 0;
  34095. this._blendingFactor = 0;
  34096. this._originalBlendValue = null;
  34097. };
  34098. Animation.prototype.isStopped = function () {
  34099. return this._stopped;
  34100. };
  34101. Animation.prototype.getKeys = function () {
  34102. return this._keys;
  34103. };
  34104. Animation.prototype.getHighestFrame = function () {
  34105. var ret = 0;
  34106. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  34107. if (ret < this._keys[key].frame) {
  34108. ret = this._keys[key].frame;
  34109. }
  34110. }
  34111. return ret;
  34112. };
  34113. Animation.prototype.getEasingFunction = function () {
  34114. return this._easingFunction;
  34115. };
  34116. Animation.prototype.setEasingFunction = function (easingFunction) {
  34117. this._easingFunction = easingFunction;
  34118. };
  34119. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  34120. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  34121. };
  34122. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34123. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34124. };
  34125. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  34126. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  34127. };
  34128. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34129. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  34130. };
  34131. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  34132. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  34133. };
  34134. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34135. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34136. };
  34137. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  34138. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  34139. };
  34140. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34141. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34142. };
  34143. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  34144. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  34145. };
  34146. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  34147. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  34148. };
  34149. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  34150. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  34151. };
  34152. Animation.prototype.clone = function () {
  34153. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  34154. clone.enableBlending = this.enableBlending;
  34155. clone.blendingSpeed = this.blendingSpeed;
  34156. if (this._keys) {
  34157. clone.setKeys(this._keys);
  34158. }
  34159. if (this._ranges) {
  34160. clone._ranges = {};
  34161. for (var name in this._ranges) {
  34162. clone._ranges[name] = this._ranges[name].clone();
  34163. }
  34164. }
  34165. return clone;
  34166. };
  34167. Animation.prototype.setKeys = function (values) {
  34168. this._keys = values.slice(0);
  34169. this._offsetsCache = {};
  34170. this._highLimitsCache = {};
  34171. };
  34172. Animation.prototype._getKeyValue = function (value) {
  34173. if (typeof value === "function") {
  34174. return value();
  34175. }
  34176. return value;
  34177. };
  34178. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  34179. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  34180. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  34181. }
  34182. this.currentFrame = currentFrame;
  34183. // Try to get a hash to find the right key
  34184. 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));
  34185. if (this._keys[startKeyIndex].frame >= currentFrame) {
  34186. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  34187. startKeyIndex--;
  34188. }
  34189. }
  34190. for (var key = startKeyIndex; key < this._keys.length; key++) {
  34191. var endKey = this._keys[key + 1];
  34192. if (endKey.frame >= currentFrame) {
  34193. var startKey = this._keys[key];
  34194. var startValue = this._getKeyValue(startKey.value);
  34195. var endValue = this._getKeyValue(endKey.value);
  34196. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  34197. var frameDelta = endKey.frame - startKey.frame;
  34198. // gradient : percent of currentFrame between the frame inf and the frame sup
  34199. var gradient = (currentFrame - startKey.frame) / frameDelta;
  34200. // check for easingFunction and correction of gradient
  34201. if (this._easingFunction != null) {
  34202. gradient = this._easingFunction.ease(gradient);
  34203. }
  34204. switch (this.dataType) {
  34205. // Float
  34206. case Animation.ANIMATIONTYPE_FLOAT:
  34207. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  34208. switch (loopMode) {
  34209. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34210. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34211. return floatValue;
  34212. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34213. return offsetValue * repeatCount + floatValue;
  34214. }
  34215. break;
  34216. // Quaternion
  34217. case Animation.ANIMATIONTYPE_QUATERNION:
  34218. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  34219. switch (loopMode) {
  34220. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34221. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34222. return quatValue;
  34223. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34224. return quatValue.add(offsetValue.scale(repeatCount));
  34225. }
  34226. return quatValue;
  34227. // Vector3
  34228. case Animation.ANIMATIONTYPE_VECTOR3:
  34229. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  34230. switch (loopMode) {
  34231. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34232. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34233. return vec3Value;
  34234. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34235. return vec3Value.add(offsetValue.scale(repeatCount));
  34236. }
  34237. // Vector2
  34238. case Animation.ANIMATIONTYPE_VECTOR2:
  34239. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  34240. switch (loopMode) {
  34241. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34242. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34243. return vec2Value;
  34244. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34245. return vec2Value.add(offsetValue.scale(repeatCount));
  34246. }
  34247. // Size
  34248. case Animation.ANIMATIONTYPE_SIZE:
  34249. switch (loopMode) {
  34250. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34251. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34252. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  34253. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34254. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34255. }
  34256. // Color3
  34257. case Animation.ANIMATIONTYPE_COLOR3:
  34258. switch (loopMode) {
  34259. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34260. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34261. return this.color3InterpolateFunction(startValue, endValue, gradient);
  34262. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34263. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34264. }
  34265. // Matrix
  34266. case Animation.ANIMATIONTYPE_MATRIX:
  34267. switch (loopMode) {
  34268. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34269. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34270. if (this.allowMatricesInterpolation) {
  34271. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  34272. }
  34273. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34274. return startValue;
  34275. }
  34276. default:
  34277. break;
  34278. }
  34279. break;
  34280. }
  34281. }
  34282. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  34283. };
  34284. Animation.prototype.setValue = function (currentValue, blend) {
  34285. if (blend === void 0) { blend = false; }
  34286. // Set value
  34287. var path;
  34288. var destination;
  34289. if (this.targetPropertyPath.length > 1) {
  34290. var property = this._target[this.targetPropertyPath[0]];
  34291. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  34292. property = property[this.targetPropertyPath[index]];
  34293. }
  34294. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  34295. destination = property;
  34296. }
  34297. else {
  34298. path = this.targetPropertyPath[0];
  34299. destination = this._target;
  34300. }
  34301. // Blending
  34302. if (this.enableBlending && this._blendingFactor <= 1.0) {
  34303. if (!this._originalBlendValue) {
  34304. if (destination[path].clone) {
  34305. this._originalBlendValue = destination[path].clone();
  34306. }
  34307. else {
  34308. this._originalBlendValue = destination[path];
  34309. }
  34310. }
  34311. if (this._originalBlendValue.prototype) {
  34312. if (this._originalBlendValue.prototype.Lerp) {
  34313. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  34314. }
  34315. else {
  34316. destination[path] = currentValue;
  34317. }
  34318. }
  34319. else if (this._originalBlendValue.m) {
  34320. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  34321. }
  34322. else {
  34323. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  34324. }
  34325. this._blendingFactor += this.blendingSpeed;
  34326. }
  34327. else {
  34328. destination[path] = currentValue;
  34329. }
  34330. if (this._target.markAsDirty) {
  34331. this._target.markAsDirty(this.targetProperty);
  34332. }
  34333. };
  34334. Animation.prototype.goToFrame = function (frame) {
  34335. if (frame < this._keys[0].frame) {
  34336. frame = this._keys[0].frame;
  34337. }
  34338. else if (frame > this._keys[this._keys.length - 1].frame) {
  34339. frame = this._keys[this._keys.length - 1].frame;
  34340. }
  34341. var currentValue = this._interpolate(frame, 0, this.loopMode);
  34342. this.setValue(currentValue);
  34343. };
  34344. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  34345. if (blend === void 0) { blend = false; }
  34346. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  34347. this._stopped = true;
  34348. return false;
  34349. }
  34350. var returnValue = true;
  34351. // Adding a start key at frame 0 if missing
  34352. if (this._keys[0].frame !== 0) {
  34353. var newKey = { frame: 0, value: this._keys[0].value };
  34354. this._keys.splice(0, 0, newKey);
  34355. }
  34356. // Check limits
  34357. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  34358. from = this._keys[0].frame;
  34359. }
  34360. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  34361. to = this._keys[this._keys.length - 1].frame;
  34362. }
  34363. //to and from cannot be the same key
  34364. if (from === to) {
  34365. from++;
  34366. }
  34367. // Compute ratio
  34368. var range = to - from;
  34369. var offsetValue;
  34370. // ratio represents the frame delta between from and to
  34371. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  34372. var highLimitValue = 0;
  34373. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  34374. returnValue = false;
  34375. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  34376. }
  34377. else {
  34378. // Get max value if required
  34379. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  34380. var keyOffset = to.toString() + from.toString();
  34381. if (!this._offsetsCache[keyOffset]) {
  34382. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34383. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34384. switch (this.dataType) {
  34385. // Float
  34386. case Animation.ANIMATIONTYPE_FLOAT:
  34387. this._offsetsCache[keyOffset] = toValue - fromValue;
  34388. break;
  34389. // Quaternion
  34390. case Animation.ANIMATIONTYPE_QUATERNION:
  34391. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34392. break;
  34393. // Vector3
  34394. case Animation.ANIMATIONTYPE_VECTOR3:
  34395. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34396. // Vector2
  34397. case Animation.ANIMATIONTYPE_VECTOR2:
  34398. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34399. // Size
  34400. case Animation.ANIMATIONTYPE_SIZE:
  34401. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34402. // Color3
  34403. case Animation.ANIMATIONTYPE_COLOR3:
  34404. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34405. default:
  34406. break;
  34407. }
  34408. this._highLimitsCache[keyOffset] = toValue;
  34409. }
  34410. highLimitValue = this._highLimitsCache[keyOffset];
  34411. offsetValue = this._offsetsCache[keyOffset];
  34412. }
  34413. }
  34414. if (offsetValue === undefined) {
  34415. switch (this.dataType) {
  34416. // Float
  34417. case Animation.ANIMATIONTYPE_FLOAT:
  34418. offsetValue = 0;
  34419. break;
  34420. // Quaternion
  34421. case Animation.ANIMATIONTYPE_QUATERNION:
  34422. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  34423. break;
  34424. // Vector3
  34425. case Animation.ANIMATIONTYPE_VECTOR3:
  34426. offsetValue = BABYLON.Vector3.Zero();
  34427. break;
  34428. // Vector2
  34429. case Animation.ANIMATIONTYPE_VECTOR2:
  34430. offsetValue = BABYLON.Vector2.Zero();
  34431. break;
  34432. // Size
  34433. case Animation.ANIMATIONTYPE_SIZE:
  34434. offsetValue = BABYLON.Size.Zero();
  34435. break;
  34436. // Color3
  34437. case Animation.ANIMATIONTYPE_COLOR3:
  34438. offsetValue = BABYLON.Color3.Black();
  34439. }
  34440. }
  34441. // Compute value
  34442. var repeatCount = (ratio / range) >> 0;
  34443. var currentFrame = returnValue ? from + ratio % range : to;
  34444. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  34445. // Set value
  34446. this.setValue(currentValue);
  34447. // Check events
  34448. for (var index = 0; index < this._events.length; index++) {
  34449. if (currentFrame >= this._events[index].frame) {
  34450. var event = this._events[index];
  34451. if (!event.isDone) {
  34452. // If event should be done only once, remove it.
  34453. if (event.onlyOnce) {
  34454. this._events.splice(index, 1);
  34455. index--;
  34456. }
  34457. event.isDone = true;
  34458. event.action();
  34459. } // Don't do anything if the event has already be done.
  34460. }
  34461. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  34462. // reset event, the animation is looping
  34463. this._events[index].isDone = false;
  34464. }
  34465. }
  34466. if (!returnValue) {
  34467. this._stopped = true;
  34468. }
  34469. return returnValue;
  34470. };
  34471. Animation.prototype.serialize = function () {
  34472. var serializationObject = {};
  34473. serializationObject.name = this.name;
  34474. serializationObject.property = this.targetProperty;
  34475. serializationObject.framePerSecond = this.framePerSecond;
  34476. serializationObject.dataType = this.dataType;
  34477. serializationObject.loopBehavior = this.loopMode;
  34478. serializationObject.enableBlending = this.enableBlending;
  34479. serializationObject.blendingSpeed = this.blendingSpeed;
  34480. var dataType = this.dataType;
  34481. serializationObject.keys = [];
  34482. var keys = this.getKeys();
  34483. for (var index = 0; index < keys.length; index++) {
  34484. var animationKey = keys[index];
  34485. var key = {};
  34486. key.frame = animationKey.frame;
  34487. switch (dataType) {
  34488. case Animation.ANIMATIONTYPE_FLOAT:
  34489. key.values = [animationKey.value];
  34490. break;
  34491. case Animation.ANIMATIONTYPE_QUATERNION:
  34492. case Animation.ANIMATIONTYPE_MATRIX:
  34493. case Animation.ANIMATIONTYPE_VECTOR3:
  34494. case Animation.ANIMATIONTYPE_COLOR3:
  34495. key.values = animationKey.value.asArray();
  34496. break;
  34497. }
  34498. serializationObject.keys.push(key);
  34499. }
  34500. serializationObject.ranges = [];
  34501. for (var name in this._ranges) {
  34502. var range = {};
  34503. range.name = name;
  34504. range.from = this._ranges[name].from;
  34505. range.to = this._ranges[name].to;
  34506. serializationObject.ranges.push(range);
  34507. }
  34508. return serializationObject;
  34509. };
  34510. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  34511. get: function () {
  34512. return Animation._ANIMATIONTYPE_FLOAT;
  34513. },
  34514. enumerable: true,
  34515. configurable: true
  34516. });
  34517. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  34518. get: function () {
  34519. return Animation._ANIMATIONTYPE_VECTOR3;
  34520. },
  34521. enumerable: true,
  34522. configurable: true
  34523. });
  34524. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  34525. get: function () {
  34526. return Animation._ANIMATIONTYPE_VECTOR2;
  34527. },
  34528. enumerable: true,
  34529. configurable: true
  34530. });
  34531. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  34532. get: function () {
  34533. return Animation._ANIMATIONTYPE_SIZE;
  34534. },
  34535. enumerable: true,
  34536. configurable: true
  34537. });
  34538. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  34539. get: function () {
  34540. return Animation._ANIMATIONTYPE_QUATERNION;
  34541. },
  34542. enumerable: true,
  34543. configurable: true
  34544. });
  34545. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  34546. get: function () {
  34547. return Animation._ANIMATIONTYPE_MATRIX;
  34548. },
  34549. enumerable: true,
  34550. configurable: true
  34551. });
  34552. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  34553. get: function () {
  34554. return Animation._ANIMATIONTYPE_COLOR3;
  34555. },
  34556. enumerable: true,
  34557. configurable: true
  34558. });
  34559. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  34560. get: function () {
  34561. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  34562. },
  34563. enumerable: true,
  34564. configurable: true
  34565. });
  34566. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  34567. get: function () {
  34568. return Animation._ANIMATIONLOOPMODE_CYCLE;
  34569. },
  34570. enumerable: true,
  34571. configurable: true
  34572. });
  34573. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  34574. get: function () {
  34575. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  34576. },
  34577. enumerable: true,
  34578. configurable: true
  34579. });
  34580. Animation.Parse = function (parsedAnimation) {
  34581. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  34582. var dataType = parsedAnimation.dataType;
  34583. var keys = [];
  34584. var data;
  34585. var index;
  34586. if (parsedAnimation.enableBlending) {
  34587. animation.enableBlending = parsedAnimation.enableBlending;
  34588. }
  34589. if (parsedAnimation.blendingSpeed) {
  34590. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  34591. }
  34592. for (index = 0; index < parsedAnimation.keys.length; index++) {
  34593. var key = parsedAnimation.keys[index];
  34594. switch (dataType) {
  34595. case Animation.ANIMATIONTYPE_FLOAT:
  34596. data = key.values[0];
  34597. break;
  34598. case Animation.ANIMATIONTYPE_QUATERNION:
  34599. data = BABYLON.Quaternion.FromArray(key.values);
  34600. break;
  34601. case Animation.ANIMATIONTYPE_MATRIX:
  34602. data = BABYLON.Matrix.FromArray(key.values);
  34603. break;
  34604. case Animation.ANIMATIONTYPE_COLOR3:
  34605. data = BABYLON.Color3.FromArray(key.values);
  34606. break;
  34607. case Animation.ANIMATIONTYPE_VECTOR3:
  34608. default:
  34609. data = BABYLON.Vector3.FromArray(key.values);
  34610. break;
  34611. }
  34612. keys.push({
  34613. frame: key.frame,
  34614. value: data
  34615. });
  34616. }
  34617. animation.setKeys(keys);
  34618. if (parsedAnimation.ranges) {
  34619. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  34620. data = parsedAnimation.ranges[index];
  34621. animation.createRange(data.name, data.from, data.to);
  34622. }
  34623. }
  34624. return animation;
  34625. };
  34626. Animation.AppendSerializedAnimations = function (source, destination) {
  34627. if (source.animations) {
  34628. destination.animations = [];
  34629. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  34630. var animation = source.animations[animationIndex];
  34631. destination.animations.push(animation.serialize());
  34632. }
  34633. }
  34634. };
  34635. return Animation;
  34636. }());
  34637. // Statics
  34638. Animation._ANIMATIONTYPE_FLOAT = 0;
  34639. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  34640. Animation._ANIMATIONTYPE_QUATERNION = 2;
  34641. Animation._ANIMATIONTYPE_MATRIX = 3;
  34642. Animation._ANIMATIONTYPE_COLOR3 = 4;
  34643. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  34644. Animation._ANIMATIONTYPE_SIZE = 6;
  34645. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  34646. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  34647. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  34648. BABYLON.Animation = Animation;
  34649. })(BABYLON || (BABYLON = {}));
  34650. //# sourceMappingURL=babylon.animation.js.map
  34651. var BABYLON;
  34652. (function (BABYLON) {
  34653. var Animatable = (function () {
  34654. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  34655. if (fromFrame === void 0) { fromFrame = 0; }
  34656. if (toFrame === void 0) { toFrame = 100; }
  34657. if (loopAnimation === void 0) { loopAnimation = false; }
  34658. if (speedRatio === void 0) { speedRatio = 1.0; }
  34659. this.target = target;
  34660. this.fromFrame = fromFrame;
  34661. this.toFrame = toFrame;
  34662. this.loopAnimation = loopAnimation;
  34663. this.speedRatio = speedRatio;
  34664. this.onAnimationEnd = onAnimationEnd;
  34665. this._localDelayOffset = null;
  34666. this._pausedDelay = null;
  34667. this._animations = new Array();
  34668. this._paused = false;
  34669. this.animationStarted = false;
  34670. if (animations) {
  34671. this.appendAnimations(target, animations);
  34672. }
  34673. this._scene = scene;
  34674. scene._activeAnimatables.push(this);
  34675. }
  34676. // Methods
  34677. Animatable.prototype.getAnimations = function () {
  34678. return this._animations;
  34679. };
  34680. Animatable.prototype.appendAnimations = function (target, animations) {
  34681. for (var index = 0; index < animations.length; index++) {
  34682. var animation = animations[index];
  34683. animation._target = target;
  34684. this._animations.push(animation);
  34685. }
  34686. };
  34687. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  34688. var animations = this._animations;
  34689. for (var index = 0; index < animations.length; index++) {
  34690. if (animations[index].targetProperty === property) {
  34691. return animations[index];
  34692. }
  34693. }
  34694. return null;
  34695. };
  34696. Animatable.prototype.reset = function () {
  34697. var animations = this._animations;
  34698. for (var index = 0; index < animations.length; index++) {
  34699. animations[index].reset();
  34700. }
  34701. this._localDelayOffset = null;
  34702. this._pausedDelay = null;
  34703. };
  34704. Animatable.prototype.enableBlending = function (blendingSpeed) {
  34705. var animations = this._animations;
  34706. for (var index = 0; index < animations.length; index++) {
  34707. animations[index].enableBlending = true;
  34708. animations[index].blendingSpeed = blendingSpeed;
  34709. }
  34710. };
  34711. Animatable.prototype.disableBlending = function () {
  34712. var animations = this._animations;
  34713. for (var index = 0; index < animations.length; index++) {
  34714. animations[index].enableBlending = false;
  34715. }
  34716. };
  34717. Animatable.prototype.goToFrame = function (frame) {
  34718. var animations = this._animations;
  34719. if (animations[0]) {
  34720. var fps = animations[0].framePerSecond;
  34721. var currentFrame = animations[0].currentFrame;
  34722. var adjustTime = frame - currentFrame;
  34723. var delay = adjustTime * 1000 / fps;
  34724. this._localDelayOffset -= delay;
  34725. }
  34726. for (var index = 0; index < animations.length; index++) {
  34727. animations[index].goToFrame(frame);
  34728. }
  34729. };
  34730. Animatable.prototype.pause = function () {
  34731. if (this._paused) {
  34732. return;
  34733. }
  34734. this._paused = true;
  34735. };
  34736. Animatable.prototype.restart = function () {
  34737. this._paused = false;
  34738. };
  34739. Animatable.prototype.stop = function (animationName) {
  34740. if (animationName) {
  34741. var idx = this._scene._activeAnimatables.indexOf(this);
  34742. if (idx > -1) {
  34743. var animations = this._animations;
  34744. for (var index = animations.length - 1; index >= 0; index--) {
  34745. if (typeof animationName === "string" && animations[index].name != animationName) {
  34746. continue;
  34747. }
  34748. animations[index].reset();
  34749. animations.splice(index, 1);
  34750. }
  34751. if (animations.length == 0) {
  34752. this._scene._activeAnimatables.splice(idx, 1);
  34753. if (this.onAnimationEnd) {
  34754. this.onAnimationEnd();
  34755. }
  34756. }
  34757. }
  34758. }
  34759. else {
  34760. var index = this._scene._activeAnimatables.indexOf(this);
  34761. if (index > -1) {
  34762. this._scene._activeAnimatables.splice(index, 1);
  34763. var animations = this._animations;
  34764. for (var index = 0; index < animations.length; index++) {
  34765. animations[index].reset();
  34766. }
  34767. if (this.onAnimationEnd) {
  34768. this.onAnimationEnd();
  34769. }
  34770. }
  34771. }
  34772. };
  34773. Animatable.prototype._animate = function (delay) {
  34774. if (this._paused) {
  34775. this.animationStarted = false;
  34776. if (this._pausedDelay === null) {
  34777. this._pausedDelay = delay;
  34778. }
  34779. return true;
  34780. }
  34781. if (this._localDelayOffset === null) {
  34782. this._localDelayOffset = delay;
  34783. }
  34784. else if (this._pausedDelay !== null) {
  34785. this._localDelayOffset += delay - this._pausedDelay;
  34786. this._pausedDelay = null;
  34787. }
  34788. // Animating
  34789. var running = false;
  34790. var animations = this._animations;
  34791. var index;
  34792. for (index = 0; index < animations.length; index++) {
  34793. var animation = animations[index];
  34794. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  34795. running = running || isRunning;
  34796. }
  34797. this.animationStarted = running;
  34798. if (!running) {
  34799. // Remove from active animatables
  34800. index = this._scene._activeAnimatables.indexOf(this);
  34801. this._scene._activeAnimatables.splice(index, 1);
  34802. }
  34803. if (!running && this.onAnimationEnd) {
  34804. this.onAnimationEnd();
  34805. this.onAnimationEnd = null;
  34806. }
  34807. return running;
  34808. };
  34809. return Animatable;
  34810. }());
  34811. BABYLON.Animatable = Animatable;
  34812. })(BABYLON || (BABYLON = {}));
  34813. //# sourceMappingURL=babylon.animatable.js.map
  34814. var BABYLON;
  34815. (function (BABYLON) {
  34816. var EasingFunction = (function () {
  34817. function EasingFunction() {
  34818. // Properties
  34819. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  34820. }
  34821. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  34822. get: function () {
  34823. return EasingFunction._EASINGMODE_EASEIN;
  34824. },
  34825. enumerable: true,
  34826. configurable: true
  34827. });
  34828. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  34829. get: function () {
  34830. return EasingFunction._EASINGMODE_EASEOUT;
  34831. },
  34832. enumerable: true,
  34833. configurable: true
  34834. });
  34835. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  34836. get: function () {
  34837. return EasingFunction._EASINGMODE_EASEINOUT;
  34838. },
  34839. enumerable: true,
  34840. configurable: true
  34841. });
  34842. EasingFunction.prototype.setEasingMode = function (easingMode) {
  34843. var n = Math.min(Math.max(easingMode, 0), 2);
  34844. this._easingMode = n;
  34845. };
  34846. EasingFunction.prototype.getEasingMode = function () {
  34847. return this._easingMode;
  34848. };
  34849. EasingFunction.prototype.easeInCore = function (gradient) {
  34850. throw new Error('You must implement this method');
  34851. };
  34852. EasingFunction.prototype.ease = function (gradient) {
  34853. switch (this._easingMode) {
  34854. case EasingFunction.EASINGMODE_EASEIN:
  34855. return this.easeInCore(gradient);
  34856. case EasingFunction.EASINGMODE_EASEOUT:
  34857. return (1 - this.easeInCore(1 - gradient));
  34858. }
  34859. if (gradient >= 0.5) {
  34860. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  34861. }
  34862. return (this.easeInCore(gradient * 2) * 0.5);
  34863. };
  34864. return EasingFunction;
  34865. }());
  34866. //Statics
  34867. EasingFunction._EASINGMODE_EASEIN = 0;
  34868. EasingFunction._EASINGMODE_EASEOUT = 1;
  34869. EasingFunction._EASINGMODE_EASEINOUT = 2;
  34870. BABYLON.EasingFunction = EasingFunction;
  34871. var CircleEase = (function (_super) {
  34872. __extends(CircleEase, _super);
  34873. function CircleEase() {
  34874. return _super !== null && _super.apply(this, arguments) || this;
  34875. }
  34876. CircleEase.prototype.easeInCore = function (gradient) {
  34877. gradient = Math.max(0, Math.min(1, gradient));
  34878. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  34879. };
  34880. return CircleEase;
  34881. }(EasingFunction));
  34882. BABYLON.CircleEase = CircleEase;
  34883. var BackEase = (function (_super) {
  34884. __extends(BackEase, _super);
  34885. function BackEase(amplitude) {
  34886. if (amplitude === void 0) { amplitude = 1; }
  34887. var _this = _super.call(this) || this;
  34888. _this.amplitude = amplitude;
  34889. return _this;
  34890. }
  34891. BackEase.prototype.easeInCore = function (gradient) {
  34892. var num = Math.max(0, this.amplitude);
  34893. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  34894. };
  34895. return BackEase;
  34896. }(EasingFunction));
  34897. BABYLON.BackEase = BackEase;
  34898. var BounceEase = (function (_super) {
  34899. __extends(BounceEase, _super);
  34900. function BounceEase(bounces, bounciness) {
  34901. if (bounces === void 0) { bounces = 3; }
  34902. if (bounciness === void 0) { bounciness = 2; }
  34903. var _this = _super.call(this) || this;
  34904. _this.bounces = bounces;
  34905. _this.bounciness = bounciness;
  34906. return _this;
  34907. }
  34908. BounceEase.prototype.easeInCore = function (gradient) {
  34909. var y = Math.max(0.0, this.bounces);
  34910. var bounciness = this.bounciness;
  34911. if (bounciness <= 1.0) {
  34912. bounciness = 1.001;
  34913. }
  34914. var num9 = Math.pow(bounciness, y);
  34915. var num5 = 1.0 - bounciness;
  34916. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  34917. var num15 = gradient * num4;
  34918. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  34919. var num3 = Math.floor(num65);
  34920. var num13 = num3 + 1.0;
  34921. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  34922. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  34923. var num7 = (num8 + num12) * 0.5;
  34924. var num6 = gradient - num7;
  34925. var num2 = num7 - num8;
  34926. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  34927. };
  34928. return BounceEase;
  34929. }(EasingFunction));
  34930. BABYLON.BounceEase = BounceEase;
  34931. var CubicEase = (function (_super) {
  34932. __extends(CubicEase, _super);
  34933. function CubicEase() {
  34934. return _super !== null && _super.apply(this, arguments) || this;
  34935. }
  34936. CubicEase.prototype.easeInCore = function (gradient) {
  34937. return (gradient * gradient * gradient);
  34938. };
  34939. return CubicEase;
  34940. }(EasingFunction));
  34941. BABYLON.CubicEase = CubicEase;
  34942. var ElasticEase = (function (_super) {
  34943. __extends(ElasticEase, _super);
  34944. function ElasticEase(oscillations, springiness) {
  34945. if (oscillations === void 0) { oscillations = 3; }
  34946. if (springiness === void 0) { springiness = 3; }
  34947. var _this = _super.call(this) || this;
  34948. _this.oscillations = oscillations;
  34949. _this.springiness = springiness;
  34950. return _this;
  34951. }
  34952. ElasticEase.prototype.easeInCore = function (gradient) {
  34953. var num2;
  34954. var num3 = Math.max(0.0, this.oscillations);
  34955. var num = Math.max(0.0, this.springiness);
  34956. if (num == 0) {
  34957. num2 = gradient;
  34958. }
  34959. else {
  34960. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  34961. }
  34962. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  34963. };
  34964. return ElasticEase;
  34965. }(EasingFunction));
  34966. BABYLON.ElasticEase = ElasticEase;
  34967. var ExponentialEase = (function (_super) {
  34968. __extends(ExponentialEase, _super);
  34969. function ExponentialEase(exponent) {
  34970. if (exponent === void 0) { exponent = 2; }
  34971. var _this = _super.call(this) || this;
  34972. _this.exponent = exponent;
  34973. return _this;
  34974. }
  34975. ExponentialEase.prototype.easeInCore = function (gradient) {
  34976. if (this.exponent <= 0) {
  34977. return gradient;
  34978. }
  34979. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  34980. };
  34981. return ExponentialEase;
  34982. }(EasingFunction));
  34983. BABYLON.ExponentialEase = ExponentialEase;
  34984. var PowerEase = (function (_super) {
  34985. __extends(PowerEase, _super);
  34986. function PowerEase(power) {
  34987. if (power === void 0) { power = 2; }
  34988. var _this = _super.call(this) || this;
  34989. _this.power = power;
  34990. return _this;
  34991. }
  34992. PowerEase.prototype.easeInCore = function (gradient) {
  34993. var y = Math.max(0.0, this.power);
  34994. return Math.pow(gradient, y);
  34995. };
  34996. return PowerEase;
  34997. }(EasingFunction));
  34998. BABYLON.PowerEase = PowerEase;
  34999. var QuadraticEase = (function (_super) {
  35000. __extends(QuadraticEase, _super);
  35001. function QuadraticEase() {
  35002. return _super !== null && _super.apply(this, arguments) || this;
  35003. }
  35004. QuadraticEase.prototype.easeInCore = function (gradient) {
  35005. return (gradient * gradient);
  35006. };
  35007. return QuadraticEase;
  35008. }(EasingFunction));
  35009. BABYLON.QuadraticEase = QuadraticEase;
  35010. var QuarticEase = (function (_super) {
  35011. __extends(QuarticEase, _super);
  35012. function QuarticEase() {
  35013. return _super !== null && _super.apply(this, arguments) || this;
  35014. }
  35015. QuarticEase.prototype.easeInCore = function (gradient) {
  35016. return (gradient * gradient * gradient * gradient);
  35017. };
  35018. return QuarticEase;
  35019. }(EasingFunction));
  35020. BABYLON.QuarticEase = QuarticEase;
  35021. var QuinticEase = (function (_super) {
  35022. __extends(QuinticEase, _super);
  35023. function QuinticEase() {
  35024. return _super !== null && _super.apply(this, arguments) || this;
  35025. }
  35026. QuinticEase.prototype.easeInCore = function (gradient) {
  35027. return (gradient * gradient * gradient * gradient * gradient);
  35028. };
  35029. return QuinticEase;
  35030. }(EasingFunction));
  35031. BABYLON.QuinticEase = QuinticEase;
  35032. var SineEase = (function (_super) {
  35033. __extends(SineEase, _super);
  35034. function SineEase() {
  35035. return _super !== null && _super.apply(this, arguments) || this;
  35036. }
  35037. SineEase.prototype.easeInCore = function (gradient) {
  35038. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  35039. };
  35040. return SineEase;
  35041. }(EasingFunction));
  35042. BABYLON.SineEase = SineEase;
  35043. var BezierCurveEase = (function (_super) {
  35044. __extends(BezierCurveEase, _super);
  35045. function BezierCurveEase(x1, y1, x2, y2) {
  35046. if (x1 === void 0) { x1 = 0; }
  35047. if (y1 === void 0) { y1 = 0; }
  35048. if (x2 === void 0) { x2 = 1; }
  35049. if (y2 === void 0) { y2 = 1; }
  35050. var _this = _super.call(this) || this;
  35051. _this.x1 = x1;
  35052. _this.y1 = y1;
  35053. _this.x2 = x2;
  35054. _this.y2 = y2;
  35055. return _this;
  35056. }
  35057. BezierCurveEase.prototype.easeInCore = function (gradient) {
  35058. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  35059. };
  35060. return BezierCurveEase;
  35061. }(EasingFunction));
  35062. BABYLON.BezierCurveEase = BezierCurveEase;
  35063. })(BABYLON || (BABYLON = {}));
  35064. //# sourceMappingURL=babylon.easing.js.map
  35065. var BABYLON;
  35066. (function (BABYLON) {
  35067. var Condition = (function () {
  35068. function Condition(actionManager) {
  35069. this._actionManager = actionManager;
  35070. }
  35071. Condition.prototype.isValid = function () {
  35072. return true;
  35073. };
  35074. Condition.prototype._getProperty = function (propertyPath) {
  35075. return this._actionManager._getProperty(propertyPath);
  35076. };
  35077. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  35078. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35079. };
  35080. Condition.prototype.serialize = function () {
  35081. };
  35082. Condition.prototype._serialize = function (serializedCondition) {
  35083. return {
  35084. type: 2,
  35085. children: [],
  35086. name: serializedCondition.name,
  35087. properties: serializedCondition.properties
  35088. };
  35089. };
  35090. return Condition;
  35091. }());
  35092. BABYLON.Condition = Condition;
  35093. var ValueCondition = (function (_super) {
  35094. __extends(ValueCondition, _super);
  35095. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  35096. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  35097. var _this = _super.call(this, actionManager) || this;
  35098. _this.propertyPath = propertyPath;
  35099. _this.value = value;
  35100. _this.operator = operator;
  35101. _this._target = target;
  35102. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  35103. _this._property = _this._getProperty(_this.propertyPath);
  35104. return _this;
  35105. }
  35106. Object.defineProperty(ValueCondition, "IsEqual", {
  35107. get: function () {
  35108. return ValueCondition._IsEqual;
  35109. },
  35110. enumerable: true,
  35111. configurable: true
  35112. });
  35113. Object.defineProperty(ValueCondition, "IsDifferent", {
  35114. get: function () {
  35115. return ValueCondition._IsDifferent;
  35116. },
  35117. enumerable: true,
  35118. configurable: true
  35119. });
  35120. Object.defineProperty(ValueCondition, "IsGreater", {
  35121. get: function () {
  35122. return ValueCondition._IsGreater;
  35123. },
  35124. enumerable: true,
  35125. configurable: true
  35126. });
  35127. Object.defineProperty(ValueCondition, "IsLesser", {
  35128. get: function () {
  35129. return ValueCondition._IsLesser;
  35130. },
  35131. enumerable: true,
  35132. configurable: true
  35133. });
  35134. // Methods
  35135. ValueCondition.prototype.isValid = function () {
  35136. switch (this.operator) {
  35137. case ValueCondition.IsGreater:
  35138. return this._effectiveTarget[this._property] > this.value;
  35139. case ValueCondition.IsLesser:
  35140. return this._effectiveTarget[this._property] < this.value;
  35141. case ValueCondition.IsEqual:
  35142. case ValueCondition.IsDifferent:
  35143. var check;
  35144. if (this.value.equals) {
  35145. check = this.value.equals(this._effectiveTarget[this._property]);
  35146. }
  35147. else {
  35148. check = this.value === this._effectiveTarget[this._property];
  35149. }
  35150. return this.operator === ValueCondition.IsEqual ? check : !check;
  35151. }
  35152. return false;
  35153. };
  35154. ValueCondition.prototype.serialize = function () {
  35155. return this._serialize({
  35156. name: "ValueCondition",
  35157. properties: [
  35158. BABYLON.Action._GetTargetProperty(this._target),
  35159. { name: "propertyPath", value: this.propertyPath },
  35160. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35161. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  35162. ]
  35163. });
  35164. };
  35165. ValueCondition.GetOperatorName = function (operator) {
  35166. switch (operator) {
  35167. case ValueCondition._IsEqual: return "IsEqual";
  35168. case ValueCondition._IsDifferent: return "IsDifferent";
  35169. case ValueCondition._IsGreater: return "IsGreater";
  35170. case ValueCondition._IsLesser: return "IsLesser";
  35171. default: return "";
  35172. }
  35173. };
  35174. return ValueCondition;
  35175. }(Condition));
  35176. // Statics
  35177. ValueCondition._IsEqual = 0;
  35178. ValueCondition._IsDifferent = 1;
  35179. ValueCondition._IsGreater = 2;
  35180. ValueCondition._IsLesser = 3;
  35181. BABYLON.ValueCondition = ValueCondition;
  35182. var PredicateCondition = (function (_super) {
  35183. __extends(PredicateCondition, _super);
  35184. function PredicateCondition(actionManager, predicate) {
  35185. var _this = _super.call(this, actionManager) || this;
  35186. _this.predicate = predicate;
  35187. return _this;
  35188. }
  35189. PredicateCondition.prototype.isValid = function () {
  35190. return this.predicate();
  35191. };
  35192. return PredicateCondition;
  35193. }(Condition));
  35194. BABYLON.PredicateCondition = PredicateCondition;
  35195. var StateCondition = (function (_super) {
  35196. __extends(StateCondition, _super);
  35197. function StateCondition(actionManager, target, value) {
  35198. var _this = _super.call(this, actionManager) || this;
  35199. _this.value = value;
  35200. _this._target = target;
  35201. return _this;
  35202. }
  35203. // Methods
  35204. StateCondition.prototype.isValid = function () {
  35205. return this._target.state === this.value;
  35206. };
  35207. StateCondition.prototype.serialize = function () {
  35208. return this._serialize({
  35209. name: "StateCondition",
  35210. properties: [
  35211. BABYLON.Action._GetTargetProperty(this._target),
  35212. { name: "value", value: this.value }
  35213. ]
  35214. });
  35215. };
  35216. return StateCondition;
  35217. }(Condition));
  35218. BABYLON.StateCondition = StateCondition;
  35219. })(BABYLON || (BABYLON = {}));
  35220. //# sourceMappingURL=babylon.condition.js.map
  35221. var BABYLON;
  35222. (function (BABYLON) {
  35223. var Action = (function () {
  35224. function Action(triggerOptions, condition) {
  35225. this.triggerOptions = triggerOptions;
  35226. if (triggerOptions.parameter) {
  35227. this.trigger = triggerOptions.trigger;
  35228. this._triggerParameter = triggerOptions.parameter;
  35229. }
  35230. else {
  35231. this.trigger = triggerOptions;
  35232. }
  35233. this._nextActiveAction = this;
  35234. this._condition = condition;
  35235. }
  35236. // Methods
  35237. Action.prototype._prepare = function () {
  35238. };
  35239. Action.prototype.getTriggerParameter = function () {
  35240. return this._triggerParameter;
  35241. };
  35242. Action.prototype._executeCurrent = function (evt) {
  35243. if (this._nextActiveAction._condition) {
  35244. var condition = this._nextActiveAction._condition;
  35245. var currentRenderId = this._actionManager.getScene().getRenderId();
  35246. // We cache the current evaluation for the current frame
  35247. if (condition._evaluationId === currentRenderId) {
  35248. if (!condition._currentResult) {
  35249. return;
  35250. }
  35251. }
  35252. else {
  35253. condition._evaluationId = currentRenderId;
  35254. if (!condition.isValid()) {
  35255. condition._currentResult = false;
  35256. return;
  35257. }
  35258. condition._currentResult = true;
  35259. }
  35260. }
  35261. this._nextActiveAction.execute(evt);
  35262. this.skipToNextActiveAction();
  35263. };
  35264. Action.prototype.execute = function (evt) {
  35265. };
  35266. Action.prototype.skipToNextActiveAction = function () {
  35267. if (this._nextActiveAction._child) {
  35268. if (!this._nextActiveAction._child._actionManager) {
  35269. this._nextActiveAction._child._actionManager = this._actionManager;
  35270. }
  35271. this._nextActiveAction = this._nextActiveAction._child;
  35272. }
  35273. else {
  35274. this._nextActiveAction = this;
  35275. }
  35276. };
  35277. Action.prototype.then = function (action) {
  35278. this._child = action;
  35279. action._actionManager = this._actionManager;
  35280. action._prepare();
  35281. return action;
  35282. };
  35283. Action.prototype._getProperty = function (propertyPath) {
  35284. return this._actionManager._getProperty(propertyPath);
  35285. };
  35286. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35287. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35288. };
  35289. Action.prototype.serialize = function (parent) {
  35290. };
  35291. // Called by BABYLON.Action objects in serialize(...). Internal use
  35292. Action.prototype._serialize = function (serializedAction, parent) {
  35293. var serializationObject = {
  35294. type: 1,
  35295. children: [],
  35296. name: serializedAction.name,
  35297. properties: serializedAction.properties || []
  35298. };
  35299. // Serialize child
  35300. if (this._child) {
  35301. this._child.serialize(serializationObject);
  35302. }
  35303. // Check if "this" has a condition
  35304. if (this._condition) {
  35305. var serializedCondition = this._condition.serialize();
  35306. serializedCondition.children.push(serializationObject);
  35307. if (parent) {
  35308. parent.children.push(serializedCondition);
  35309. }
  35310. return serializedCondition;
  35311. }
  35312. if (parent) {
  35313. parent.children.push(serializationObject);
  35314. }
  35315. return serializationObject;
  35316. };
  35317. return Action;
  35318. }());
  35319. Action._SerializeValueAsString = function (value) {
  35320. if (typeof value === "number") {
  35321. return value.toString();
  35322. }
  35323. if (typeof value === "boolean") {
  35324. return value ? "true" : "false";
  35325. }
  35326. if (value instanceof BABYLON.Vector2) {
  35327. return value.x + ", " + value.y;
  35328. }
  35329. if (value instanceof BABYLON.Vector3) {
  35330. return value.x + ", " + value.y + ", " + value.z;
  35331. }
  35332. if (value instanceof BABYLON.Color3) {
  35333. return value.r + ", " + value.g + ", " + value.b;
  35334. }
  35335. if (value instanceof BABYLON.Color4) {
  35336. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35337. }
  35338. return value; // string
  35339. };
  35340. Action._GetTargetProperty = function (target) {
  35341. return {
  35342. name: "target",
  35343. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35344. : target instanceof BABYLON.Light ? "LightProperties"
  35345. : target instanceof BABYLON.Camera ? "CameraProperties"
  35346. : "SceneProperties",
  35347. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35348. };
  35349. };
  35350. BABYLON.Action = Action;
  35351. })(BABYLON || (BABYLON = {}));
  35352. //# sourceMappingURL=babylon.action.js.map
  35353. var BABYLON;
  35354. (function (BABYLON) {
  35355. /**
  35356. * ActionEvent is the event beint sent when an action is triggered.
  35357. */
  35358. var ActionEvent = (function () {
  35359. /**
  35360. * @constructor
  35361. * @param source The mesh or sprite that triggered the action.
  35362. * @param pointerX The X mouse cursor position at the time of the event
  35363. * @param pointerY The Y mouse cursor position at the time of the event
  35364. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35365. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35366. */
  35367. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35368. this.source = source;
  35369. this.pointerX = pointerX;
  35370. this.pointerY = pointerY;
  35371. this.meshUnderPointer = meshUnderPointer;
  35372. this.sourceEvent = sourceEvent;
  35373. this.additionalData = additionalData;
  35374. }
  35375. /**
  35376. * Helper function to auto-create an ActionEvent from a source mesh.
  35377. * @param source The source mesh that triggered the event
  35378. * @param evt {Event} The original (browser) event
  35379. */
  35380. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35381. var scene = source.getScene();
  35382. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35383. };
  35384. /**
  35385. * Helper function to auto-create an ActionEvent from a source mesh.
  35386. * @param source The source sprite that triggered the event
  35387. * @param scene Scene associated with the sprite
  35388. * @param evt {Event} The original (browser) event
  35389. */
  35390. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35391. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35392. };
  35393. /**
  35394. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35395. * @param scene the scene where the event occurred
  35396. * @param evt {Event} The original (browser) event
  35397. */
  35398. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35399. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35400. };
  35401. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35402. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35403. };
  35404. return ActionEvent;
  35405. }());
  35406. BABYLON.ActionEvent = ActionEvent;
  35407. /**
  35408. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35409. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35410. */
  35411. var ActionManager = (function () {
  35412. function ActionManager(scene) {
  35413. // Members
  35414. this.actions = new Array();
  35415. this.hoverCursor = '';
  35416. this._scene = scene;
  35417. scene._actionManagers.push(this);
  35418. }
  35419. Object.defineProperty(ActionManager, "NothingTrigger", {
  35420. get: function () {
  35421. return ActionManager._NothingTrigger;
  35422. },
  35423. enumerable: true,
  35424. configurable: true
  35425. });
  35426. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35427. get: function () {
  35428. return ActionManager._OnPickTrigger;
  35429. },
  35430. enumerable: true,
  35431. configurable: true
  35432. });
  35433. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35434. get: function () {
  35435. return ActionManager._OnLeftPickTrigger;
  35436. },
  35437. enumerable: true,
  35438. configurable: true
  35439. });
  35440. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35441. get: function () {
  35442. return ActionManager._OnRightPickTrigger;
  35443. },
  35444. enumerable: true,
  35445. configurable: true
  35446. });
  35447. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35448. get: function () {
  35449. return ActionManager._OnCenterPickTrigger;
  35450. },
  35451. enumerable: true,
  35452. configurable: true
  35453. });
  35454. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35455. get: function () {
  35456. return ActionManager._OnPickDownTrigger;
  35457. },
  35458. enumerable: true,
  35459. configurable: true
  35460. });
  35461. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  35462. get: function () {
  35463. return ActionManager._OnDoublePickTrigger;
  35464. },
  35465. enumerable: true,
  35466. configurable: true
  35467. });
  35468. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35469. get: function () {
  35470. return ActionManager._OnPickUpTrigger;
  35471. },
  35472. enumerable: true,
  35473. configurable: true
  35474. });
  35475. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35476. /// This trigger will only be raised if you also declared a OnPickDown
  35477. get: function () {
  35478. return ActionManager._OnPickOutTrigger;
  35479. },
  35480. enumerable: true,
  35481. configurable: true
  35482. });
  35483. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35484. get: function () {
  35485. return ActionManager._OnLongPressTrigger;
  35486. },
  35487. enumerable: true,
  35488. configurable: true
  35489. });
  35490. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35491. get: function () {
  35492. return ActionManager._OnPointerOverTrigger;
  35493. },
  35494. enumerable: true,
  35495. configurable: true
  35496. });
  35497. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35498. get: function () {
  35499. return ActionManager._OnPointerOutTrigger;
  35500. },
  35501. enumerable: true,
  35502. configurable: true
  35503. });
  35504. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  35505. get: function () {
  35506. return ActionManager._OnEveryFrameTrigger;
  35507. },
  35508. enumerable: true,
  35509. configurable: true
  35510. });
  35511. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  35512. get: function () {
  35513. return ActionManager._OnIntersectionEnterTrigger;
  35514. },
  35515. enumerable: true,
  35516. configurable: true
  35517. });
  35518. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  35519. get: function () {
  35520. return ActionManager._OnIntersectionExitTrigger;
  35521. },
  35522. enumerable: true,
  35523. configurable: true
  35524. });
  35525. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  35526. get: function () {
  35527. return ActionManager._OnKeyDownTrigger;
  35528. },
  35529. enumerable: true,
  35530. configurable: true
  35531. });
  35532. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  35533. get: function () {
  35534. return ActionManager._OnKeyUpTrigger;
  35535. },
  35536. enumerable: true,
  35537. configurable: true
  35538. });
  35539. // Methods
  35540. ActionManager.prototype.dispose = function () {
  35541. var index = this._scene._actionManagers.indexOf(this);
  35542. for (var i = 0; i < this.actions.length; i++) {
  35543. var action = this.actions[i];
  35544. ActionManager.Triggers[action.trigger]--;
  35545. if (ActionManager.Triggers[action.trigger] === 0) {
  35546. delete ActionManager.Triggers[action.trigger];
  35547. }
  35548. }
  35549. if (index > -1) {
  35550. this._scene._actionManagers.splice(index, 1);
  35551. }
  35552. };
  35553. ActionManager.prototype.getScene = function () {
  35554. return this._scene;
  35555. };
  35556. /**
  35557. * Does this action manager handles actions of any of the given triggers
  35558. * @param {number[]} triggers - the triggers to be tested
  35559. * @return {boolean} whether one (or more) of the triggers is handeled
  35560. */
  35561. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  35562. for (var index = 0; index < this.actions.length; index++) {
  35563. var action = this.actions[index];
  35564. if (triggers.indexOf(action.trigger) > -1) {
  35565. return true;
  35566. }
  35567. }
  35568. return false;
  35569. };
  35570. /**
  35571. * Does this action manager handles actions of a given trigger
  35572. * @param {number} trigger - the trigger to be tested
  35573. * @return {boolean} whether the trigger is handeled
  35574. */
  35575. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  35576. for (var index = 0; index < this.actions.length; index++) {
  35577. var action = this.actions[index];
  35578. if (action.trigger === trigger) {
  35579. return true;
  35580. }
  35581. }
  35582. return false;
  35583. };
  35584. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  35585. /**
  35586. * Does this action manager has pointer triggers
  35587. * @return {boolean} whether or not it has pointer triggers
  35588. */
  35589. get: function () {
  35590. for (var index = 0; index < this.actions.length; index++) {
  35591. var action = this.actions[index];
  35592. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  35593. return true;
  35594. }
  35595. }
  35596. return false;
  35597. },
  35598. enumerable: true,
  35599. configurable: true
  35600. });
  35601. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  35602. /**
  35603. * Does this action manager has pick triggers
  35604. * @return {boolean} whether or not it has pick triggers
  35605. */
  35606. get: function () {
  35607. for (var index = 0; index < this.actions.length; index++) {
  35608. var action = this.actions[index];
  35609. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  35610. return true;
  35611. }
  35612. }
  35613. return false;
  35614. },
  35615. enumerable: true,
  35616. configurable: true
  35617. });
  35618. Object.defineProperty(ActionManager, "HasTriggers", {
  35619. /**
  35620. * Does exist one action manager with at least one trigger
  35621. * @return {boolean} whether or not it exists one action manager with one trigger
  35622. **/
  35623. get: function () {
  35624. for (var t in ActionManager.Triggers) {
  35625. if (ActionManager.Triggers.hasOwnProperty(t)) {
  35626. return true;
  35627. }
  35628. }
  35629. return false;
  35630. },
  35631. enumerable: true,
  35632. configurable: true
  35633. });
  35634. Object.defineProperty(ActionManager, "HasPickTriggers", {
  35635. /**
  35636. * Does exist one action manager with at least one pick trigger
  35637. * @return {boolean} whether or not it exists one action manager with one pick trigger
  35638. **/
  35639. get: function () {
  35640. for (var t in ActionManager.Triggers) {
  35641. if (ActionManager.Triggers.hasOwnProperty(t)) {
  35642. var t_int = parseInt(t);
  35643. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  35644. return true;
  35645. }
  35646. }
  35647. }
  35648. return false;
  35649. },
  35650. enumerable: true,
  35651. configurable: true
  35652. });
  35653. /**
  35654. * Does exist one action manager that handles actions of a given trigger
  35655. * @param {number} trigger - the trigger to be tested
  35656. * @return {boolean} whether the trigger is handeled by at least one action manager
  35657. **/
  35658. ActionManager.HasSpecificTrigger = function (trigger) {
  35659. for (var t in ActionManager.Triggers) {
  35660. if (ActionManager.Triggers.hasOwnProperty(t)) {
  35661. var t_int = parseInt(t);
  35662. if (t_int === trigger) {
  35663. return true;
  35664. }
  35665. }
  35666. }
  35667. return false;
  35668. };
  35669. /**
  35670. * Registers an action to this action manager
  35671. * @param {BABYLON.Action} action - the action to be registered
  35672. * @return {BABYLON.Action} the action amended (prepared) after registration
  35673. */
  35674. ActionManager.prototype.registerAction = function (action) {
  35675. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  35676. if (this.getScene().actionManager !== this) {
  35677. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  35678. return null;
  35679. }
  35680. }
  35681. this.actions.push(action);
  35682. if (ActionManager.Triggers[action.trigger]) {
  35683. ActionManager.Triggers[action.trigger]++;
  35684. }
  35685. else {
  35686. ActionManager.Triggers[action.trigger] = 1;
  35687. }
  35688. action._actionManager = this;
  35689. action._prepare();
  35690. return action;
  35691. };
  35692. /**
  35693. * Process a specific trigger
  35694. * @param {number} trigger - the trigger to process
  35695. * @param evt {BABYLON.ActionEvent} the event details to be processed
  35696. */
  35697. ActionManager.prototype.processTrigger = function (trigger, evt) {
  35698. for (var index = 0; index < this.actions.length; index++) {
  35699. var action = this.actions[index];
  35700. if (action.trigger === trigger) {
  35701. if (trigger === ActionManager.OnKeyUpTrigger
  35702. || trigger === ActionManager.OnKeyDownTrigger) {
  35703. var parameter = action.getTriggerParameter();
  35704. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  35705. if (!parameter.toLowerCase) {
  35706. continue;
  35707. }
  35708. var lowerCase = parameter.toLowerCase();
  35709. if (lowerCase !== evt.sourceEvent.key) {
  35710. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  35711. var actualkey = String.fromCharCode(unicode).toLowerCase();
  35712. if (actualkey !== lowerCase) {
  35713. continue;
  35714. }
  35715. }
  35716. }
  35717. }
  35718. action._executeCurrent(evt);
  35719. }
  35720. }
  35721. };
  35722. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  35723. var properties = propertyPath.split(".");
  35724. for (var index = 0; index < properties.length - 1; index++) {
  35725. target = target[properties[index]];
  35726. }
  35727. return target;
  35728. };
  35729. ActionManager.prototype._getProperty = function (propertyPath) {
  35730. var properties = propertyPath.split(".");
  35731. return properties[properties.length - 1];
  35732. };
  35733. ActionManager.prototype.serialize = function (name) {
  35734. var root = {
  35735. children: [],
  35736. name: name,
  35737. type: 3,
  35738. properties: [] // Empty for root but required
  35739. };
  35740. for (var i = 0; i < this.actions.length; i++) {
  35741. var triggerObject = {
  35742. type: 0,
  35743. children: [],
  35744. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  35745. properties: []
  35746. };
  35747. var triggerOptions = this.actions[i].triggerOptions;
  35748. if (triggerOptions && typeof triggerOptions !== "number") {
  35749. if (triggerOptions.parameter instanceof BABYLON.Node) {
  35750. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  35751. }
  35752. else {
  35753. var parameter = {};
  35754. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  35755. if (triggerOptions.parameter.mesh) {
  35756. parameter._meshId = triggerOptions.parameter.mesh.id;
  35757. }
  35758. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  35759. }
  35760. }
  35761. // Serialize child action, recursively
  35762. this.actions[i].serialize(triggerObject);
  35763. // Add serialized trigger
  35764. root.children.push(triggerObject);
  35765. }
  35766. return root;
  35767. };
  35768. ActionManager.Parse = function (parsedActions, object, scene) {
  35769. var actionManager = new BABYLON.ActionManager(scene);
  35770. if (object === null)
  35771. scene.actionManager = actionManager;
  35772. else
  35773. object.actionManager = actionManager;
  35774. // instanciate a new object
  35775. var instanciate = function (name, params) {
  35776. var newInstance = Object.create(BABYLON[name].prototype);
  35777. newInstance.constructor.apply(newInstance, params);
  35778. return newInstance;
  35779. };
  35780. var parseParameter = function (name, value, target, propertyPath) {
  35781. if (propertyPath === null) {
  35782. // String, boolean or float
  35783. var floatValue = parseFloat(value);
  35784. if (value === "true" || value === "false")
  35785. return value === "true";
  35786. else
  35787. return isNaN(floatValue) ? value : floatValue;
  35788. }
  35789. var effectiveTarget = propertyPath.split(".");
  35790. var values = value.split(",");
  35791. // Get effective Target
  35792. for (var i = 0; i < effectiveTarget.length; i++) {
  35793. target = target[effectiveTarget[i]];
  35794. }
  35795. // Return appropriate value with its type
  35796. if (typeof (target) === "boolean")
  35797. return values[0] === "true";
  35798. if (typeof (target) === "string")
  35799. return values[0];
  35800. // Parameters with multiple values such as Vector3 etc.
  35801. var split = new Array();
  35802. for (var i = 0; i < values.length; i++)
  35803. split.push(parseFloat(values[i]));
  35804. if (target instanceof BABYLON.Vector3)
  35805. return BABYLON.Vector3.FromArray(split);
  35806. if (target instanceof BABYLON.Vector4)
  35807. return BABYLON.Vector4.FromArray(split);
  35808. if (target instanceof BABYLON.Color3)
  35809. return BABYLON.Color3.FromArray(split);
  35810. if (target instanceof BABYLON.Color4)
  35811. return BABYLON.Color4.FromArray(split);
  35812. return parseFloat(values[0]);
  35813. };
  35814. // traverse graph per trigger
  35815. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  35816. if (combineArray === void 0) { combineArray = null; }
  35817. if (parsedAction.detached)
  35818. return;
  35819. var parameters = new Array();
  35820. var target = null;
  35821. var propertyPath = null;
  35822. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  35823. // Parameters
  35824. if (parsedAction.type === 2)
  35825. parameters.push(actionManager);
  35826. else
  35827. parameters.push(trigger);
  35828. if (combine) {
  35829. var actions = new Array();
  35830. for (var j = 0; j < parsedAction.combine.length; j++) {
  35831. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  35832. }
  35833. parameters.push(actions);
  35834. }
  35835. else {
  35836. for (var i = 0; i < parsedAction.properties.length; i++) {
  35837. var value = parsedAction.properties[i].value;
  35838. var name = parsedAction.properties[i].name;
  35839. var targetType = parsedAction.properties[i].targetType;
  35840. if (name === "target")
  35841. if (targetType !== null && targetType === "SceneProperties")
  35842. value = target = scene;
  35843. else
  35844. value = target = scene.getNodeByName(value);
  35845. else if (name === "parent")
  35846. value = scene.getNodeByName(value);
  35847. else if (name === "sound")
  35848. value = scene.getSoundByName(value);
  35849. else if (name !== "propertyPath") {
  35850. if (parsedAction.type === 2 && name === "operator")
  35851. value = BABYLON.ValueCondition[value];
  35852. else
  35853. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  35854. }
  35855. else {
  35856. propertyPath = value;
  35857. }
  35858. parameters.push(value);
  35859. }
  35860. }
  35861. if (combineArray === null) {
  35862. parameters.push(condition);
  35863. }
  35864. else {
  35865. parameters.push(null);
  35866. }
  35867. // If interpolate value action
  35868. if (parsedAction.name === "InterpolateValueAction") {
  35869. var param = parameters[parameters.length - 2];
  35870. parameters[parameters.length - 1] = param;
  35871. parameters[parameters.length - 2] = condition;
  35872. }
  35873. // Action or condition(s) and not CombineAction
  35874. var newAction = instanciate(parsedAction.name, parameters);
  35875. if (newAction instanceof BABYLON.Condition && condition !== null) {
  35876. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  35877. if (action)
  35878. action.then(nothing);
  35879. else
  35880. actionManager.registerAction(nothing);
  35881. action = nothing;
  35882. }
  35883. if (combineArray === null) {
  35884. if (newAction instanceof BABYLON.Condition) {
  35885. condition = newAction;
  35886. newAction = action;
  35887. }
  35888. else {
  35889. condition = null;
  35890. if (action)
  35891. action.then(newAction);
  35892. else
  35893. actionManager.registerAction(newAction);
  35894. }
  35895. }
  35896. else {
  35897. combineArray.push(newAction);
  35898. }
  35899. for (var i = 0; i < parsedAction.children.length; i++)
  35900. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  35901. };
  35902. // triggers
  35903. for (var i = 0; i < parsedActions.children.length; i++) {
  35904. var triggerParams;
  35905. var trigger = parsedActions.children[i];
  35906. if (trigger.properties.length > 0) {
  35907. var param = trigger.properties[0].value;
  35908. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  35909. if (value._meshId) {
  35910. value.mesh = scene.getMeshByID(value._meshId);
  35911. }
  35912. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  35913. }
  35914. else
  35915. triggerParams = BABYLON.ActionManager[trigger.name];
  35916. for (var j = 0; j < trigger.children.length; j++) {
  35917. if (!trigger.detached)
  35918. traverse(trigger.children[j], triggerParams, null, null);
  35919. }
  35920. }
  35921. };
  35922. ActionManager.GetTriggerName = function (trigger) {
  35923. switch (trigger) {
  35924. case 0: return "NothingTrigger";
  35925. case 1: return "OnPickTrigger";
  35926. case 2: return "OnLeftPickTrigger";
  35927. case 3: return "OnRightPickTrigger";
  35928. case 4: return "OnCenterPickTrigger";
  35929. case 5: return "OnPickDownTrigger";
  35930. case 6: return "OnPickUpTrigger";
  35931. case 7: return "OnLongPressTrigger";
  35932. case 8: return "OnPointerOverTrigger";
  35933. case 9: return "OnPointerOutTrigger";
  35934. case 10: return "OnEveryFrameTrigger";
  35935. case 11: return "OnIntersectionEnterTrigger";
  35936. case 12: return "OnIntersectionExitTrigger";
  35937. case 13: return "OnKeyDownTrigger";
  35938. case 14: return "OnKeyUpTrigger";
  35939. case 15: return "OnPickOutTrigger";
  35940. default: return "";
  35941. }
  35942. };
  35943. return ActionManager;
  35944. }());
  35945. // Statics
  35946. ActionManager._NothingTrigger = 0;
  35947. ActionManager._OnPickTrigger = 1;
  35948. ActionManager._OnLeftPickTrigger = 2;
  35949. ActionManager._OnRightPickTrigger = 3;
  35950. ActionManager._OnCenterPickTrigger = 4;
  35951. ActionManager._OnPickDownTrigger = 5;
  35952. ActionManager._OnDoublePickTrigger = 6;
  35953. ActionManager._OnPickUpTrigger = 7;
  35954. ActionManager._OnLongPressTrigger = 8;
  35955. ActionManager._OnPointerOverTrigger = 9;
  35956. ActionManager._OnPointerOutTrigger = 10;
  35957. ActionManager._OnEveryFrameTrigger = 11;
  35958. ActionManager._OnIntersectionEnterTrigger = 12;
  35959. ActionManager._OnIntersectionExitTrigger = 13;
  35960. ActionManager._OnKeyDownTrigger = 14;
  35961. ActionManager._OnKeyUpTrigger = 15;
  35962. ActionManager._OnPickOutTrigger = 16;
  35963. ActionManager.Triggers = {};
  35964. BABYLON.ActionManager = ActionManager;
  35965. })(BABYLON || (BABYLON = {}));
  35966. //# sourceMappingURL=babylon.actionManager.js.map
  35967. var BABYLON;
  35968. (function (BABYLON) {
  35969. var InterpolateValueAction = (function (_super) {
  35970. __extends(InterpolateValueAction, _super);
  35971. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  35972. if (duration === void 0) { duration = 1000; }
  35973. var _this = _super.call(this, triggerOptions, condition) || this;
  35974. _this.propertyPath = propertyPath;
  35975. _this.value = value;
  35976. _this.duration = duration;
  35977. _this.stopOtherAnimations = stopOtherAnimations;
  35978. _this.onInterpolationDone = onInterpolationDone;
  35979. _this._target = _this._effectiveTarget = target;
  35980. return _this;
  35981. }
  35982. InterpolateValueAction.prototype._prepare = function () {
  35983. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35984. this._property = this._getProperty(this.propertyPath);
  35985. };
  35986. InterpolateValueAction.prototype.execute = function () {
  35987. var scene = this._actionManager.getScene();
  35988. var keys = [
  35989. {
  35990. frame: 0,
  35991. value: this._effectiveTarget[this._property]
  35992. }, {
  35993. frame: 100,
  35994. value: this.value
  35995. }
  35996. ];
  35997. var dataType;
  35998. if (typeof this.value === "number") {
  35999. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  36000. }
  36001. else if (this.value instanceof BABYLON.Color3) {
  36002. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  36003. }
  36004. else if (this.value instanceof BABYLON.Vector3) {
  36005. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  36006. }
  36007. else if (this.value instanceof BABYLON.Matrix) {
  36008. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  36009. }
  36010. else if (this.value instanceof BABYLON.Quaternion) {
  36011. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  36012. }
  36013. else {
  36014. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  36015. return;
  36016. }
  36017. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36018. animation.setKeys(keys);
  36019. if (this.stopOtherAnimations) {
  36020. scene.stopAnimation(this._effectiveTarget);
  36021. }
  36022. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  36023. };
  36024. InterpolateValueAction.prototype.serialize = function (parent) {
  36025. return _super.prototype._serialize.call(this, {
  36026. name: "InterpolateValueAction",
  36027. properties: [
  36028. BABYLON.Action._GetTargetProperty(this._target),
  36029. { name: "propertyPath", value: this.propertyPath },
  36030. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36031. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  36032. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  36033. ]
  36034. }, parent);
  36035. };
  36036. return InterpolateValueAction;
  36037. }(BABYLON.Action));
  36038. BABYLON.InterpolateValueAction = InterpolateValueAction;
  36039. })(BABYLON || (BABYLON = {}));
  36040. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  36041. var BABYLON;
  36042. (function (BABYLON) {
  36043. var SwitchBooleanAction = (function (_super) {
  36044. __extends(SwitchBooleanAction, _super);
  36045. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  36046. var _this = _super.call(this, triggerOptions, condition) || this;
  36047. _this.propertyPath = propertyPath;
  36048. _this._target = _this._effectiveTarget = target;
  36049. return _this;
  36050. }
  36051. SwitchBooleanAction.prototype._prepare = function () {
  36052. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36053. this._property = this._getProperty(this.propertyPath);
  36054. };
  36055. SwitchBooleanAction.prototype.execute = function () {
  36056. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  36057. };
  36058. SwitchBooleanAction.prototype.serialize = function (parent) {
  36059. return _super.prototype._serialize.call(this, {
  36060. name: "SwitchBooleanAction",
  36061. properties: [
  36062. BABYLON.Action._GetTargetProperty(this._target),
  36063. { name: "propertyPath", value: this.propertyPath }
  36064. ]
  36065. }, parent);
  36066. };
  36067. return SwitchBooleanAction;
  36068. }(BABYLON.Action));
  36069. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  36070. var SetStateAction = (function (_super) {
  36071. __extends(SetStateAction, _super);
  36072. function SetStateAction(triggerOptions, target, value, condition) {
  36073. var _this = _super.call(this, triggerOptions, condition) || this;
  36074. _this.value = value;
  36075. _this._target = target;
  36076. return _this;
  36077. }
  36078. SetStateAction.prototype.execute = function () {
  36079. this._target.state = this.value;
  36080. };
  36081. SetStateAction.prototype.serialize = function (parent) {
  36082. return _super.prototype._serialize.call(this, {
  36083. name: "SetStateAction",
  36084. properties: [
  36085. BABYLON.Action._GetTargetProperty(this._target),
  36086. { name: "value", value: this.value }
  36087. ]
  36088. }, parent);
  36089. };
  36090. return SetStateAction;
  36091. }(BABYLON.Action));
  36092. BABYLON.SetStateAction = SetStateAction;
  36093. var SetValueAction = (function (_super) {
  36094. __extends(SetValueAction, _super);
  36095. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  36096. var _this = _super.call(this, triggerOptions, condition) || this;
  36097. _this.propertyPath = propertyPath;
  36098. _this.value = value;
  36099. _this._target = _this._effectiveTarget = target;
  36100. return _this;
  36101. }
  36102. SetValueAction.prototype._prepare = function () {
  36103. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36104. this._property = this._getProperty(this.propertyPath);
  36105. };
  36106. SetValueAction.prototype.execute = function () {
  36107. this._effectiveTarget[this._property] = this.value;
  36108. if (this._target.markAsDirty) {
  36109. this._target.markAsDirty(this._property);
  36110. }
  36111. };
  36112. SetValueAction.prototype.serialize = function (parent) {
  36113. return _super.prototype._serialize.call(this, {
  36114. name: "SetValueAction",
  36115. properties: [
  36116. BABYLON.Action._GetTargetProperty(this._target),
  36117. { name: "propertyPath", value: this.propertyPath },
  36118. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36119. ]
  36120. }, parent);
  36121. };
  36122. return SetValueAction;
  36123. }(BABYLON.Action));
  36124. BABYLON.SetValueAction = SetValueAction;
  36125. var IncrementValueAction = (function (_super) {
  36126. __extends(IncrementValueAction, _super);
  36127. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  36128. var _this = _super.call(this, triggerOptions, condition) || this;
  36129. _this.propertyPath = propertyPath;
  36130. _this.value = value;
  36131. _this._target = _this._effectiveTarget = target;
  36132. return _this;
  36133. }
  36134. IncrementValueAction.prototype._prepare = function () {
  36135. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36136. this._property = this._getProperty(this.propertyPath);
  36137. if (typeof this._effectiveTarget[this._property] !== "number") {
  36138. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  36139. }
  36140. };
  36141. IncrementValueAction.prototype.execute = function () {
  36142. this._effectiveTarget[this._property] += this.value;
  36143. if (this._target.markAsDirty) {
  36144. this._target.markAsDirty(this._property);
  36145. }
  36146. };
  36147. IncrementValueAction.prototype.serialize = function (parent) {
  36148. return _super.prototype._serialize.call(this, {
  36149. name: "IncrementValueAction",
  36150. properties: [
  36151. BABYLON.Action._GetTargetProperty(this._target),
  36152. { name: "propertyPath", value: this.propertyPath },
  36153. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36154. ]
  36155. }, parent);
  36156. };
  36157. return IncrementValueAction;
  36158. }(BABYLON.Action));
  36159. BABYLON.IncrementValueAction = IncrementValueAction;
  36160. var PlayAnimationAction = (function (_super) {
  36161. __extends(PlayAnimationAction, _super);
  36162. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  36163. var _this = _super.call(this, triggerOptions, condition) || this;
  36164. _this.from = from;
  36165. _this.to = to;
  36166. _this.loop = loop;
  36167. _this._target = target;
  36168. return _this;
  36169. }
  36170. PlayAnimationAction.prototype._prepare = function () {
  36171. };
  36172. PlayAnimationAction.prototype.execute = function () {
  36173. var scene = this._actionManager.getScene();
  36174. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  36175. };
  36176. PlayAnimationAction.prototype.serialize = function (parent) {
  36177. return _super.prototype._serialize.call(this, {
  36178. name: "PlayAnimationAction",
  36179. properties: [
  36180. BABYLON.Action._GetTargetProperty(this._target),
  36181. { name: "from", value: String(this.from) },
  36182. { name: "to", value: String(this.to) },
  36183. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  36184. ]
  36185. }, parent);
  36186. };
  36187. return PlayAnimationAction;
  36188. }(BABYLON.Action));
  36189. BABYLON.PlayAnimationAction = PlayAnimationAction;
  36190. var StopAnimationAction = (function (_super) {
  36191. __extends(StopAnimationAction, _super);
  36192. function StopAnimationAction(triggerOptions, target, condition) {
  36193. var _this = _super.call(this, triggerOptions, condition) || this;
  36194. _this._target = target;
  36195. return _this;
  36196. }
  36197. StopAnimationAction.prototype._prepare = function () {
  36198. };
  36199. StopAnimationAction.prototype.execute = function () {
  36200. var scene = this._actionManager.getScene();
  36201. scene.stopAnimation(this._target);
  36202. };
  36203. StopAnimationAction.prototype.serialize = function (parent) {
  36204. return _super.prototype._serialize.call(this, {
  36205. name: "StopAnimationAction",
  36206. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  36207. }, parent);
  36208. };
  36209. return StopAnimationAction;
  36210. }(BABYLON.Action));
  36211. BABYLON.StopAnimationAction = StopAnimationAction;
  36212. var DoNothingAction = (function (_super) {
  36213. __extends(DoNothingAction, _super);
  36214. function DoNothingAction(triggerOptions, condition) {
  36215. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36216. return _super.call(this, triggerOptions, condition) || this;
  36217. }
  36218. DoNothingAction.prototype.execute = function () {
  36219. };
  36220. DoNothingAction.prototype.serialize = function (parent) {
  36221. return _super.prototype._serialize.call(this, {
  36222. name: "DoNothingAction",
  36223. properties: []
  36224. }, parent);
  36225. };
  36226. return DoNothingAction;
  36227. }(BABYLON.Action));
  36228. BABYLON.DoNothingAction = DoNothingAction;
  36229. var CombineAction = (function (_super) {
  36230. __extends(CombineAction, _super);
  36231. function CombineAction(triggerOptions, children, condition) {
  36232. var _this = _super.call(this, triggerOptions, condition) || this;
  36233. _this.children = children;
  36234. return _this;
  36235. }
  36236. CombineAction.prototype._prepare = function () {
  36237. for (var index = 0; index < this.children.length; index++) {
  36238. this.children[index]._actionManager = this._actionManager;
  36239. this.children[index]._prepare();
  36240. }
  36241. };
  36242. CombineAction.prototype.execute = function (evt) {
  36243. for (var index = 0; index < this.children.length; index++) {
  36244. this.children[index].execute(evt);
  36245. }
  36246. };
  36247. CombineAction.prototype.serialize = function (parent) {
  36248. var serializationObject = _super.prototype._serialize.call(this, {
  36249. name: "CombineAction",
  36250. properties: [],
  36251. combine: []
  36252. }, parent);
  36253. for (var i = 0; i < this.children.length; i++) {
  36254. serializationObject.combine.push(this.children[i].serialize(null));
  36255. }
  36256. return serializationObject;
  36257. };
  36258. return CombineAction;
  36259. }(BABYLON.Action));
  36260. BABYLON.CombineAction = CombineAction;
  36261. var ExecuteCodeAction = (function (_super) {
  36262. __extends(ExecuteCodeAction, _super);
  36263. function ExecuteCodeAction(triggerOptions, func, condition) {
  36264. var _this = _super.call(this, triggerOptions, condition) || this;
  36265. _this.func = func;
  36266. return _this;
  36267. }
  36268. ExecuteCodeAction.prototype.execute = function (evt) {
  36269. this.func(evt);
  36270. };
  36271. return ExecuteCodeAction;
  36272. }(BABYLON.Action));
  36273. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36274. var SetParentAction = (function (_super) {
  36275. __extends(SetParentAction, _super);
  36276. function SetParentAction(triggerOptions, target, parent, condition) {
  36277. var _this = _super.call(this, triggerOptions, condition) || this;
  36278. _this._target = target;
  36279. _this._parent = parent;
  36280. return _this;
  36281. }
  36282. SetParentAction.prototype._prepare = function () {
  36283. };
  36284. SetParentAction.prototype.execute = function () {
  36285. if (this._target.parent === this._parent) {
  36286. return;
  36287. }
  36288. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36289. invertParentWorldMatrix.invert();
  36290. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36291. this._target.parent = this._parent;
  36292. };
  36293. SetParentAction.prototype.serialize = function (parent) {
  36294. return _super.prototype._serialize.call(this, {
  36295. name: "SetParentAction",
  36296. properties: [
  36297. BABYLON.Action._GetTargetProperty(this._target),
  36298. BABYLON.Action._GetTargetProperty(this._parent),
  36299. ]
  36300. }, parent);
  36301. };
  36302. return SetParentAction;
  36303. }(BABYLON.Action));
  36304. BABYLON.SetParentAction = SetParentAction;
  36305. var PlaySoundAction = (function (_super) {
  36306. __extends(PlaySoundAction, _super);
  36307. function PlaySoundAction(triggerOptions, sound, condition) {
  36308. var _this = _super.call(this, triggerOptions, condition) || this;
  36309. _this._sound = sound;
  36310. return _this;
  36311. }
  36312. PlaySoundAction.prototype._prepare = function () {
  36313. };
  36314. PlaySoundAction.prototype.execute = function () {
  36315. if (this._sound !== undefined)
  36316. this._sound.play();
  36317. };
  36318. PlaySoundAction.prototype.serialize = function (parent) {
  36319. return _super.prototype._serialize.call(this, {
  36320. name: "PlaySoundAction",
  36321. properties: [{ name: "sound", value: this._sound.name }]
  36322. }, parent);
  36323. };
  36324. return PlaySoundAction;
  36325. }(BABYLON.Action));
  36326. BABYLON.PlaySoundAction = PlaySoundAction;
  36327. var StopSoundAction = (function (_super) {
  36328. __extends(StopSoundAction, _super);
  36329. function StopSoundAction(triggerOptions, sound, condition) {
  36330. var _this = _super.call(this, triggerOptions, condition) || this;
  36331. _this._sound = sound;
  36332. return _this;
  36333. }
  36334. StopSoundAction.prototype._prepare = function () {
  36335. };
  36336. StopSoundAction.prototype.execute = function () {
  36337. if (this._sound !== undefined)
  36338. this._sound.stop();
  36339. };
  36340. StopSoundAction.prototype.serialize = function (parent) {
  36341. return _super.prototype._serialize.call(this, {
  36342. name: "StopSoundAction",
  36343. properties: [{ name: "sound", value: this._sound.name }]
  36344. }, parent);
  36345. };
  36346. return StopSoundAction;
  36347. }(BABYLON.Action));
  36348. BABYLON.StopSoundAction = StopSoundAction;
  36349. })(BABYLON || (BABYLON = {}));
  36350. //# sourceMappingURL=babylon.directActions.js.map
  36351. var BABYLON;
  36352. (function (BABYLON) {
  36353. var SpriteManager = (function () {
  36354. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  36355. if (epsilon === void 0) { epsilon = 0.01; }
  36356. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36357. this.name = name;
  36358. this.sprites = new Array();
  36359. this.renderingGroupId = 0;
  36360. this.layerMask = 0x0FFFFFFF;
  36361. this.fogEnabled = true;
  36362. this.isPickable = false;
  36363. /**
  36364. * An event triggered when the manager is disposed.
  36365. * @type {BABYLON.Observable}
  36366. */
  36367. this.onDisposeObservable = new BABYLON.Observable();
  36368. this._vertexBuffers = {};
  36369. this._capacity = capacity;
  36370. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  36371. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36372. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36373. if (cellSize.width && cellSize.height) {
  36374. this.cellWidth = cellSize.width;
  36375. this.cellHeight = cellSize.height;
  36376. }
  36377. else if (cellSize !== undefined) {
  36378. this.cellWidth = cellSize;
  36379. this.cellHeight = cellSize;
  36380. }
  36381. else {
  36382. return;
  36383. }
  36384. this._epsilon = epsilon;
  36385. this._scene = scene;
  36386. this._scene.spriteManagers.push(this);
  36387. var indices = [];
  36388. var index = 0;
  36389. for (var count = 0; count < capacity; count++) {
  36390. indices.push(index);
  36391. indices.push(index + 1);
  36392. indices.push(index + 2);
  36393. indices.push(index);
  36394. indices.push(index + 2);
  36395. indices.push(index + 3);
  36396. index += 4;
  36397. }
  36398. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  36399. // VBO
  36400. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  36401. this._vertexData = new Float32Array(capacity * 16 * 4);
  36402. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  36403. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  36404. var options = this._buffer.createVertexBuffer("options", 4, 4);
  36405. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  36406. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  36407. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  36408. this._vertexBuffers["options"] = options;
  36409. this._vertexBuffers["cellInfo"] = cellInfo;
  36410. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  36411. // Effects
  36412. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  36413. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  36414. }
  36415. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  36416. set: function (callback) {
  36417. if (this._onDisposeObserver) {
  36418. this.onDisposeObservable.remove(this._onDisposeObserver);
  36419. }
  36420. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36421. },
  36422. enumerable: true,
  36423. configurable: true
  36424. });
  36425. Object.defineProperty(SpriteManager.prototype, "texture", {
  36426. get: function () {
  36427. return this._spriteTexture;
  36428. },
  36429. set: function (value) {
  36430. this._spriteTexture = value;
  36431. },
  36432. enumerable: true,
  36433. configurable: true
  36434. });
  36435. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  36436. var arrayOffset = index * 16;
  36437. if (offsetX === 0)
  36438. offsetX = this._epsilon;
  36439. else if (offsetX === 1)
  36440. offsetX = 1 - this._epsilon;
  36441. if (offsetY === 0)
  36442. offsetY = this._epsilon;
  36443. else if (offsetY === 1)
  36444. offsetY = 1 - this._epsilon;
  36445. this._vertexData[arrayOffset] = sprite.position.x;
  36446. this._vertexData[arrayOffset + 1] = sprite.position.y;
  36447. this._vertexData[arrayOffset + 2] = sprite.position.z;
  36448. this._vertexData[arrayOffset + 3] = sprite.angle;
  36449. this._vertexData[arrayOffset + 4] = sprite.width;
  36450. this._vertexData[arrayOffset + 5] = sprite.height;
  36451. this._vertexData[arrayOffset + 6] = offsetX;
  36452. this._vertexData[arrayOffset + 7] = offsetY;
  36453. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  36454. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  36455. var offset = (sprite.cellIndex / rowSize) >> 0;
  36456. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  36457. this._vertexData[arrayOffset + 11] = offset;
  36458. // Color
  36459. this._vertexData[arrayOffset + 12] = sprite.color.r;
  36460. this._vertexData[arrayOffset + 13] = sprite.color.g;
  36461. this._vertexData[arrayOffset + 14] = sprite.color.b;
  36462. this._vertexData[arrayOffset + 15] = sprite.color.a;
  36463. };
  36464. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  36465. var count = Math.min(this._capacity, this.sprites.length);
  36466. var min = BABYLON.Vector3.Zero();
  36467. var max = BABYLON.Vector3.Zero();
  36468. var distance = Number.MAX_VALUE;
  36469. var currentSprite;
  36470. var cameraSpacePosition = BABYLON.Vector3.Zero();
  36471. var cameraView = camera.getViewMatrix();
  36472. for (var index = 0; index < count; index++) {
  36473. var sprite = this.sprites[index];
  36474. if (!sprite) {
  36475. continue;
  36476. }
  36477. if (predicate) {
  36478. if (!predicate(sprite)) {
  36479. continue;
  36480. }
  36481. }
  36482. else if (!sprite.isPickable) {
  36483. continue;
  36484. }
  36485. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  36486. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  36487. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  36488. if (ray.intersectsBoxMinMax(min, max)) {
  36489. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  36490. if (distance > currentDistance) {
  36491. distance = currentDistance;
  36492. currentSprite = sprite;
  36493. if (fastCheck) {
  36494. break;
  36495. }
  36496. }
  36497. }
  36498. }
  36499. if (currentSprite) {
  36500. var result = new BABYLON.PickingInfo();
  36501. result.hit = true;
  36502. result.pickedSprite = currentSprite;
  36503. result.distance = distance;
  36504. return result;
  36505. }
  36506. return null;
  36507. };
  36508. SpriteManager.prototype.render = function () {
  36509. // Check
  36510. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  36511. return;
  36512. var engine = this._scene.getEngine();
  36513. var baseSize = this._spriteTexture.getBaseSize();
  36514. // Sprites
  36515. var deltaTime = engine.getDeltaTime();
  36516. var max = Math.min(this._capacity, this.sprites.length);
  36517. var rowSize = baseSize.width / this.cellWidth;
  36518. var offset = 0;
  36519. for (var index = 0; index < max; index++) {
  36520. var sprite = this.sprites[index];
  36521. if (!sprite) {
  36522. continue;
  36523. }
  36524. sprite._animate(deltaTime);
  36525. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  36526. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  36527. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  36528. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  36529. }
  36530. this._buffer.update(this._vertexData);
  36531. // Render
  36532. var effect = this._effectBase;
  36533. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  36534. effect = this._effectFog;
  36535. }
  36536. engine.enableEffect(effect);
  36537. var viewMatrix = this._scene.getViewMatrix();
  36538. effect.setTexture("diffuseSampler", this._spriteTexture);
  36539. effect.setMatrix("view", viewMatrix);
  36540. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  36541. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  36542. // Fog
  36543. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  36544. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  36545. effect.setColor3("vFogColor", this._scene.fogColor);
  36546. }
  36547. // VBOs
  36548. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36549. // Draw order
  36550. engine.setDepthFunctionToLessOrEqual();
  36551. effect.setBool("alphaTest", true);
  36552. engine.setColorWrite(false);
  36553. engine.draw(true, 0, max * 6);
  36554. engine.setColorWrite(true);
  36555. effect.setBool("alphaTest", false);
  36556. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36557. engine.draw(true, 0, max * 6);
  36558. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36559. };
  36560. SpriteManager.prototype.dispose = function () {
  36561. if (this._buffer) {
  36562. this._buffer.dispose();
  36563. this._buffer = null;
  36564. }
  36565. if (this._indexBuffer) {
  36566. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36567. this._indexBuffer = null;
  36568. }
  36569. if (this._spriteTexture) {
  36570. this._spriteTexture.dispose();
  36571. this._spriteTexture = null;
  36572. }
  36573. // Remove from scene
  36574. var index = this._scene.spriteManagers.indexOf(this);
  36575. this._scene.spriteManagers.splice(index, 1);
  36576. // Callback
  36577. this.onDisposeObservable.notifyObservers(this);
  36578. this.onDisposeObservable.clear();
  36579. };
  36580. return SpriteManager;
  36581. }());
  36582. BABYLON.SpriteManager = SpriteManager;
  36583. })(BABYLON || (BABYLON = {}));
  36584. //# sourceMappingURL=babylon.spriteManager.js.map
  36585. var BABYLON;
  36586. (function (BABYLON) {
  36587. var Sprite = (function () {
  36588. function Sprite(name, manager) {
  36589. this.name = name;
  36590. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  36591. this.width = 1.0;
  36592. this.height = 1.0;
  36593. this.angle = 0;
  36594. this.cellIndex = 0;
  36595. this.invertU = 0;
  36596. this.invertV = 0;
  36597. this.animations = new Array();
  36598. this.isPickable = false;
  36599. this._animationStarted = false;
  36600. this._loopAnimation = false;
  36601. this._fromIndex = 0;
  36602. this._toIndex = 0;
  36603. this._delay = 0;
  36604. this._direction = 1;
  36605. this._frameCount = 0;
  36606. this._time = 0;
  36607. this._manager = manager;
  36608. this._manager.sprites.push(this);
  36609. this.position = BABYLON.Vector3.Zero();
  36610. }
  36611. Object.defineProperty(Sprite.prototype, "size", {
  36612. get: function () {
  36613. return this.width;
  36614. },
  36615. set: function (value) {
  36616. this.width = value;
  36617. this.height = value;
  36618. },
  36619. enumerable: true,
  36620. configurable: true
  36621. });
  36622. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  36623. this._fromIndex = from;
  36624. this._toIndex = to;
  36625. this._loopAnimation = loop;
  36626. this._delay = delay;
  36627. this._animationStarted = true;
  36628. this._direction = from < to ? 1 : -1;
  36629. this.cellIndex = from;
  36630. this._time = 0;
  36631. this._onAnimationEnd = onAnimationEnd;
  36632. };
  36633. Sprite.prototype.stopAnimation = function () {
  36634. this._animationStarted = false;
  36635. };
  36636. Sprite.prototype._animate = function (deltaTime) {
  36637. if (!this._animationStarted)
  36638. return;
  36639. this._time += deltaTime;
  36640. if (this._time > this._delay) {
  36641. this._time = this._time % this._delay;
  36642. this.cellIndex += this._direction;
  36643. if (this.cellIndex === this._toIndex) {
  36644. if (this._loopAnimation) {
  36645. this.cellIndex = this._fromIndex;
  36646. }
  36647. else {
  36648. this._animationStarted = false;
  36649. if (this._onAnimationEnd) {
  36650. this._onAnimationEnd();
  36651. }
  36652. if (this.disposeWhenFinishedAnimating) {
  36653. this.dispose();
  36654. }
  36655. }
  36656. }
  36657. }
  36658. };
  36659. Sprite.prototype.dispose = function () {
  36660. for (var i = 0; i < this._manager.sprites.length; i++) {
  36661. if (this._manager.sprites[i] == this) {
  36662. this._manager.sprites.splice(i, 1);
  36663. }
  36664. }
  36665. };
  36666. return Sprite;
  36667. }());
  36668. BABYLON.Sprite = Sprite;
  36669. })(BABYLON || (BABYLON = {}));
  36670. //# sourceMappingURL=babylon.sprite.js.map
  36671. var BABYLON;
  36672. (function (BABYLON) {
  36673. var IntersectionInfo = (function () {
  36674. function IntersectionInfo(bu, bv, distance) {
  36675. this.bu = bu;
  36676. this.bv = bv;
  36677. this.distance = distance;
  36678. this.faceId = 0;
  36679. this.subMeshId = 0;
  36680. }
  36681. return IntersectionInfo;
  36682. }());
  36683. BABYLON.IntersectionInfo = IntersectionInfo;
  36684. var PickingInfo = (function () {
  36685. function PickingInfo() {
  36686. this.hit = false;
  36687. this.distance = 0;
  36688. this.pickedPoint = null;
  36689. this.pickedMesh = null;
  36690. this.bu = 0;
  36691. this.bv = 0;
  36692. this.faceId = -1;
  36693. this.subMeshId = 0;
  36694. this.pickedSprite = null;
  36695. }
  36696. // Methods
  36697. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  36698. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  36699. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  36700. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36701. return null;
  36702. }
  36703. var indices = this.pickedMesh.getIndices();
  36704. var result;
  36705. if (useVerticesNormals) {
  36706. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36707. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  36708. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  36709. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  36710. normal0 = normal0.scale(this.bu);
  36711. normal1 = normal1.scale(this.bv);
  36712. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  36713. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  36714. }
  36715. else {
  36716. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36717. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  36718. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  36719. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  36720. var p1p2 = vertex1.subtract(vertex2);
  36721. var p3p2 = vertex3.subtract(vertex2);
  36722. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  36723. }
  36724. if (useWorldCoordinates) {
  36725. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  36726. }
  36727. return BABYLON.Vector3.Normalize(result);
  36728. };
  36729. PickingInfo.prototype.getTextureCoordinates = function () {
  36730. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36731. return null;
  36732. }
  36733. var indices = this.pickedMesh.getIndices();
  36734. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36735. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  36736. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  36737. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  36738. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  36739. uv1 = uv1.scale(this.bu);
  36740. uv2 = uv2.scale(this.bv);
  36741. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  36742. };
  36743. return PickingInfo;
  36744. }());
  36745. BABYLON.PickingInfo = PickingInfo;
  36746. })(BABYLON || (BABYLON = {}));
  36747. //# sourceMappingURL=babylon.pickingInfo.js.map
  36748. var BABYLON;
  36749. (function (BABYLON) {
  36750. var Ray = (function () {
  36751. function Ray(origin, direction, length) {
  36752. if (length === void 0) { length = Number.MAX_VALUE; }
  36753. this.origin = origin;
  36754. this.direction = direction;
  36755. this.length = length;
  36756. }
  36757. // Methods
  36758. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  36759. var d = 0.0;
  36760. var maxValue = Number.MAX_VALUE;
  36761. var inv;
  36762. var min;
  36763. var max;
  36764. var temp;
  36765. if (Math.abs(this.direction.x) < 0.0000001) {
  36766. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  36767. return false;
  36768. }
  36769. }
  36770. else {
  36771. inv = 1.0 / this.direction.x;
  36772. min = (minimum.x - this.origin.x) * inv;
  36773. max = (maximum.x - this.origin.x) * inv;
  36774. if (max === -Infinity) {
  36775. max = Infinity;
  36776. }
  36777. if (min > max) {
  36778. temp = min;
  36779. min = max;
  36780. max = temp;
  36781. }
  36782. d = Math.max(min, d);
  36783. maxValue = Math.min(max, maxValue);
  36784. if (d > maxValue) {
  36785. return false;
  36786. }
  36787. }
  36788. if (Math.abs(this.direction.y) < 0.0000001) {
  36789. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  36790. return false;
  36791. }
  36792. }
  36793. else {
  36794. inv = 1.0 / this.direction.y;
  36795. min = (minimum.y - this.origin.y) * inv;
  36796. max = (maximum.y - this.origin.y) * inv;
  36797. if (max === -Infinity) {
  36798. max = Infinity;
  36799. }
  36800. if (min > max) {
  36801. temp = min;
  36802. min = max;
  36803. max = temp;
  36804. }
  36805. d = Math.max(min, d);
  36806. maxValue = Math.min(max, maxValue);
  36807. if (d > maxValue) {
  36808. return false;
  36809. }
  36810. }
  36811. if (Math.abs(this.direction.z) < 0.0000001) {
  36812. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  36813. return false;
  36814. }
  36815. }
  36816. else {
  36817. inv = 1.0 / this.direction.z;
  36818. min = (minimum.z - this.origin.z) * inv;
  36819. max = (maximum.z - this.origin.z) * inv;
  36820. if (max === -Infinity) {
  36821. max = Infinity;
  36822. }
  36823. if (min > max) {
  36824. temp = min;
  36825. min = max;
  36826. max = temp;
  36827. }
  36828. d = Math.max(min, d);
  36829. maxValue = Math.min(max, maxValue);
  36830. if (d > maxValue) {
  36831. return false;
  36832. }
  36833. }
  36834. return true;
  36835. };
  36836. Ray.prototype.intersectsBox = function (box) {
  36837. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  36838. };
  36839. Ray.prototype.intersectsSphere = function (sphere) {
  36840. var x = sphere.center.x - this.origin.x;
  36841. var y = sphere.center.y - this.origin.y;
  36842. var z = sphere.center.z - this.origin.z;
  36843. var pyth = (x * x) + (y * y) + (z * z);
  36844. var rr = sphere.radius * sphere.radius;
  36845. if (pyth <= rr) {
  36846. return true;
  36847. }
  36848. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  36849. if (dot < 0.0) {
  36850. return false;
  36851. }
  36852. var temp = pyth - (dot * dot);
  36853. return temp <= rr;
  36854. };
  36855. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  36856. if (!this._edge1) {
  36857. this._edge1 = BABYLON.Vector3.Zero();
  36858. this._edge2 = BABYLON.Vector3.Zero();
  36859. this._pvec = BABYLON.Vector3.Zero();
  36860. this._tvec = BABYLON.Vector3.Zero();
  36861. this._qvec = BABYLON.Vector3.Zero();
  36862. }
  36863. vertex1.subtractToRef(vertex0, this._edge1);
  36864. vertex2.subtractToRef(vertex0, this._edge2);
  36865. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  36866. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  36867. if (det === 0) {
  36868. return null;
  36869. }
  36870. var invdet = 1 / det;
  36871. this.origin.subtractToRef(vertex0, this._tvec);
  36872. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  36873. if (bu < 0 || bu > 1.0) {
  36874. return null;
  36875. }
  36876. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  36877. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  36878. if (bv < 0 || bu + bv > 1.0) {
  36879. return null;
  36880. }
  36881. //check if the distance is longer than the predefined length.
  36882. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  36883. if (distance > this.length) {
  36884. return null;
  36885. }
  36886. return new BABYLON.IntersectionInfo(bu, bv, distance);
  36887. };
  36888. Ray.prototype.intersectsPlane = function (plane) {
  36889. var distance;
  36890. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  36891. if (Math.abs(result1) < 9.99999997475243E-07) {
  36892. return null;
  36893. }
  36894. else {
  36895. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  36896. distance = (-plane.d - result2) / result1;
  36897. if (distance < 0.0) {
  36898. if (distance < -9.99999997475243E-07) {
  36899. return null;
  36900. }
  36901. else {
  36902. return 0;
  36903. }
  36904. }
  36905. return distance;
  36906. }
  36907. };
  36908. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  36909. var tm = BABYLON.Tmp.Matrix[0];
  36910. mesh.getWorldMatrix().invertToRef(tm);
  36911. if (this._tmpRay) {
  36912. Ray.TransformToRef(this, tm, this._tmpRay);
  36913. }
  36914. else {
  36915. this._tmpRay = Ray.Transform(this, tm);
  36916. }
  36917. return mesh.intersects(this._tmpRay, fastCheck);
  36918. };
  36919. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  36920. if (results) {
  36921. results.length = 0;
  36922. }
  36923. else {
  36924. results = [];
  36925. }
  36926. for (var i = 0; i < meshes.length; i++) {
  36927. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  36928. if (pickInfo.hit) {
  36929. results.push(pickInfo);
  36930. }
  36931. }
  36932. results.sort(this._comparePickingInfo);
  36933. return results;
  36934. };
  36935. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  36936. if (pickingInfoA.distance < pickingInfoB.distance) {
  36937. return -1;
  36938. }
  36939. else if (pickingInfoA.distance > pickingInfoB.distance) {
  36940. return 1;
  36941. }
  36942. else {
  36943. return 0;
  36944. }
  36945. };
  36946. /**
  36947. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  36948. * @param sega the first point of the segment to test the intersection against
  36949. * @param segb the second point of the segment to test the intersection against
  36950. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  36951. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  36952. */
  36953. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  36954. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  36955. var u = segb.subtract(sega);
  36956. var v = rsegb.subtract(this.origin);
  36957. var w = sega.subtract(this.origin);
  36958. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  36959. var b = BABYLON.Vector3.Dot(u, v);
  36960. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  36961. var d = BABYLON.Vector3.Dot(u, w);
  36962. var e = BABYLON.Vector3.Dot(v, w);
  36963. var D = a * c - b * b; // always >= 0
  36964. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  36965. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  36966. // compute the line parameters of the two closest points
  36967. if (D < Ray.smallnum) {
  36968. sN = 0.0; // force using point P0 on segment S1
  36969. sD = 1.0; // to prevent possible division by 0.0 later
  36970. tN = e;
  36971. tD = c;
  36972. }
  36973. else {
  36974. sN = (b * e - c * d);
  36975. tN = (a * e - b * d);
  36976. if (sN < 0.0) {
  36977. sN = 0.0;
  36978. tN = e;
  36979. tD = c;
  36980. }
  36981. else if (sN > sD) {
  36982. sN = sD;
  36983. tN = e + b;
  36984. tD = c;
  36985. }
  36986. }
  36987. if (tN < 0.0) {
  36988. tN = 0.0;
  36989. // recompute sc for this edge
  36990. if (-d < 0.0) {
  36991. sN = 0.0;
  36992. }
  36993. else if (-d > a)
  36994. sN = sD;
  36995. else {
  36996. sN = -d;
  36997. sD = a;
  36998. }
  36999. }
  37000. else if (tN > tD) {
  37001. tN = tD;
  37002. // recompute sc for this edge
  37003. if ((-d + b) < 0.0) {
  37004. sN = 0;
  37005. }
  37006. else if ((-d + b) > a) {
  37007. sN = sD;
  37008. }
  37009. else {
  37010. sN = (-d + b);
  37011. sD = a;
  37012. }
  37013. }
  37014. // finally do the division to get sc and tc
  37015. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  37016. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  37017. // get the difference of the two closest points
  37018. var qtc = v.multiplyByFloats(tc, tc, tc);
  37019. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  37020. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  37021. if (isIntersected) {
  37022. return qtc.length();
  37023. }
  37024. return -1;
  37025. };
  37026. // Statics
  37027. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  37028. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  37029. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  37030. var direction = end.subtract(start);
  37031. direction.normalize();
  37032. return new Ray(start, direction);
  37033. };
  37034. /**
  37035. * 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
  37036. * transformed to the given world matrix.
  37037. * @param origin The origin point
  37038. * @param end The end point
  37039. * @param world a matrix to transform the ray to. Default is the identity matrix.
  37040. */
  37041. Ray.CreateNewFromTo = function (origin, end, world) {
  37042. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  37043. var direction = end.subtract(origin);
  37044. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  37045. direction.normalize();
  37046. return Ray.Transform(new Ray(origin, direction, length), world);
  37047. };
  37048. Ray.Transform = function (ray, matrix) {
  37049. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  37050. Ray.TransformToRef(ray, matrix, result);
  37051. return result;
  37052. };
  37053. Ray.TransformToRef = function (ray, matrix, result) {
  37054. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  37055. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  37056. result.length = ray.length;
  37057. var dir = result.direction;
  37058. var len = dir.length();
  37059. if (!(len === 0 || len === 1)) {
  37060. var num = 1.0 / len;
  37061. dir.x *= num;
  37062. dir.y *= num;
  37063. dir.z *= num;
  37064. result.length *= len;
  37065. }
  37066. };
  37067. return Ray;
  37068. }());
  37069. Ray.smallnum = 0.00000001;
  37070. Ray.rayl = 10e8;
  37071. BABYLON.Ray = Ray;
  37072. })(BABYLON || (BABYLON = {}));
  37073. //# sourceMappingURL=babylon.ray.js.map
  37074. var BABYLON;
  37075. (function (BABYLON) {
  37076. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  37077. if (boxMin.x > sphereCenter.x + sphereRadius)
  37078. return false;
  37079. if (sphereCenter.x - sphereRadius > boxMax.x)
  37080. return false;
  37081. if (boxMin.y > sphereCenter.y + sphereRadius)
  37082. return false;
  37083. if (sphereCenter.y - sphereRadius > boxMax.y)
  37084. return false;
  37085. if (boxMin.z > sphereCenter.z + sphereRadius)
  37086. return false;
  37087. if (sphereCenter.z - sphereRadius > boxMax.z)
  37088. return false;
  37089. return true;
  37090. };
  37091. var getLowestRoot = (function () {
  37092. var result = { root: 0, found: false };
  37093. return function (a, b, c, maxR) {
  37094. result.root = 0;
  37095. result.found = false;
  37096. var determinant = b * b - 4.0 * a * c;
  37097. if (determinant < 0)
  37098. return result;
  37099. var sqrtD = Math.sqrt(determinant);
  37100. var r1 = (-b - sqrtD) / (2.0 * a);
  37101. var r2 = (-b + sqrtD) / (2.0 * a);
  37102. if (r1 > r2) {
  37103. var temp = r2;
  37104. r2 = r1;
  37105. r1 = temp;
  37106. }
  37107. if (r1 > 0 && r1 < maxR) {
  37108. result.root = r1;
  37109. result.found = true;
  37110. return result;
  37111. }
  37112. if (r2 > 0 && r2 < maxR) {
  37113. result.root = r2;
  37114. result.found = true;
  37115. return result;
  37116. }
  37117. return result;
  37118. };
  37119. })();
  37120. var Collider = (function () {
  37121. function Collider() {
  37122. this.radius = new BABYLON.Vector3(1, 1, 1);
  37123. this.retry = 0;
  37124. this.basePointWorld = BABYLON.Vector3.Zero();
  37125. this.velocityWorld = BABYLON.Vector3.Zero();
  37126. this.normalizedVelocity = BABYLON.Vector3.Zero();
  37127. this._collisionPoint = BABYLON.Vector3.Zero();
  37128. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  37129. this._tempVector = BABYLON.Vector3.Zero();
  37130. this._tempVector2 = BABYLON.Vector3.Zero();
  37131. this._tempVector3 = BABYLON.Vector3.Zero();
  37132. this._tempVector4 = BABYLON.Vector3.Zero();
  37133. this._edge = BABYLON.Vector3.Zero();
  37134. this._baseToVertex = BABYLON.Vector3.Zero();
  37135. this._destinationPoint = BABYLON.Vector3.Zero();
  37136. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  37137. this._displacementVector = BABYLON.Vector3.Zero();
  37138. this._collisionMask = -1;
  37139. }
  37140. Object.defineProperty(Collider.prototype, "collisionMask", {
  37141. get: function () {
  37142. return this._collisionMask;
  37143. },
  37144. set: function (mask) {
  37145. this._collisionMask = !isNaN(mask) ? mask : -1;
  37146. },
  37147. enumerable: true,
  37148. configurable: true
  37149. });
  37150. // Methods
  37151. Collider.prototype._initialize = function (source, dir, e) {
  37152. this.velocity = dir;
  37153. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  37154. this.basePoint = source;
  37155. source.multiplyToRef(this.radius, this.basePointWorld);
  37156. dir.multiplyToRef(this.radius, this.velocityWorld);
  37157. this.velocityWorldLength = this.velocityWorld.length();
  37158. this.epsilon = e;
  37159. this.collisionFound = false;
  37160. };
  37161. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  37162. pa.subtractToRef(point, this._tempVector);
  37163. pb.subtractToRef(point, this._tempVector2);
  37164. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  37165. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37166. if (d < 0)
  37167. return false;
  37168. pc.subtractToRef(point, this._tempVector3);
  37169. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  37170. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37171. if (d < 0)
  37172. return false;
  37173. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  37174. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37175. return d >= 0;
  37176. };
  37177. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  37178. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  37179. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  37180. if (distance > this.velocityWorldLength + max + sphereRadius) {
  37181. return false;
  37182. }
  37183. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  37184. return false;
  37185. return true;
  37186. };
  37187. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  37188. var t0;
  37189. var embeddedInPlane = false;
  37190. //defensive programming, actually not needed.
  37191. if (!trianglePlaneArray) {
  37192. trianglePlaneArray = [];
  37193. }
  37194. if (!trianglePlaneArray[faceIndex]) {
  37195. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  37196. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  37197. }
  37198. var trianglePlane = trianglePlaneArray[faceIndex];
  37199. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  37200. return;
  37201. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  37202. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  37203. if (normalDotVelocity == 0) {
  37204. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  37205. return;
  37206. embeddedInPlane = true;
  37207. t0 = 0;
  37208. }
  37209. else {
  37210. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37211. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37212. if (t0 > t1) {
  37213. var temp = t1;
  37214. t1 = t0;
  37215. t0 = temp;
  37216. }
  37217. if (t0 > 1.0 || t1 < 0.0)
  37218. return;
  37219. if (t0 < 0)
  37220. t0 = 0;
  37221. if (t0 > 1.0)
  37222. t0 = 1.0;
  37223. }
  37224. this._collisionPoint.copyFromFloats(0, 0, 0);
  37225. var found = false;
  37226. var t = 1.0;
  37227. if (!embeddedInPlane) {
  37228. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  37229. this.velocity.scaleToRef(t0, this._tempVector);
  37230. this._planeIntersectionPoint.addInPlace(this._tempVector);
  37231. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  37232. found = true;
  37233. t = t0;
  37234. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  37235. }
  37236. }
  37237. if (!found) {
  37238. var velocitySquaredLength = this.velocity.lengthSquared();
  37239. var a = velocitySquaredLength;
  37240. this.basePoint.subtractToRef(p1, this._tempVector);
  37241. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37242. var c = this._tempVector.lengthSquared() - 1.0;
  37243. var lowestRoot = getLowestRoot(a, b, c, t);
  37244. if (lowestRoot.found) {
  37245. t = lowestRoot.root;
  37246. found = true;
  37247. this._collisionPoint.copyFrom(p1);
  37248. }
  37249. this.basePoint.subtractToRef(p2, this._tempVector);
  37250. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37251. c = this._tempVector.lengthSquared() - 1.0;
  37252. lowestRoot = getLowestRoot(a, b, c, t);
  37253. if (lowestRoot.found) {
  37254. t = lowestRoot.root;
  37255. found = true;
  37256. this._collisionPoint.copyFrom(p2);
  37257. }
  37258. this.basePoint.subtractToRef(p3, this._tempVector);
  37259. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37260. c = this._tempVector.lengthSquared() - 1.0;
  37261. lowestRoot = getLowestRoot(a, b, c, t);
  37262. if (lowestRoot.found) {
  37263. t = lowestRoot.root;
  37264. found = true;
  37265. this._collisionPoint.copyFrom(p3);
  37266. }
  37267. p2.subtractToRef(p1, this._edge);
  37268. p1.subtractToRef(this.basePoint, this._baseToVertex);
  37269. var edgeSquaredLength = this._edge.lengthSquared();
  37270. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37271. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37272. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37273. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37274. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37275. lowestRoot = getLowestRoot(a, b, c, t);
  37276. if (lowestRoot.found) {
  37277. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37278. if (f >= 0.0 && f <= 1.0) {
  37279. t = lowestRoot.root;
  37280. found = true;
  37281. this._edge.scaleInPlace(f);
  37282. p1.addToRef(this._edge, this._collisionPoint);
  37283. }
  37284. }
  37285. p3.subtractToRef(p2, this._edge);
  37286. p2.subtractToRef(this.basePoint, this._baseToVertex);
  37287. edgeSquaredLength = this._edge.lengthSquared();
  37288. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37289. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37290. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37291. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37292. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37293. lowestRoot = getLowestRoot(a, b, c, t);
  37294. if (lowestRoot.found) {
  37295. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37296. if (f >= 0.0 && f <= 1.0) {
  37297. t = lowestRoot.root;
  37298. found = true;
  37299. this._edge.scaleInPlace(f);
  37300. p2.addToRef(this._edge, this._collisionPoint);
  37301. }
  37302. }
  37303. p1.subtractToRef(p3, this._edge);
  37304. p3.subtractToRef(this.basePoint, this._baseToVertex);
  37305. edgeSquaredLength = this._edge.lengthSquared();
  37306. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37307. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37308. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37309. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37310. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37311. lowestRoot = getLowestRoot(a, b, c, t);
  37312. if (lowestRoot.found) {
  37313. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37314. if (f >= 0.0 && f <= 1.0) {
  37315. t = lowestRoot.root;
  37316. found = true;
  37317. this._edge.scaleInPlace(f);
  37318. p3.addToRef(this._edge, this._collisionPoint);
  37319. }
  37320. }
  37321. }
  37322. if (found) {
  37323. var distToCollision = t * this.velocity.length();
  37324. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  37325. if (!this.intersectionPoint) {
  37326. this.intersectionPoint = this._collisionPoint.clone();
  37327. }
  37328. else {
  37329. this.intersectionPoint.copyFrom(this._collisionPoint);
  37330. }
  37331. this.nearestDistance = distToCollision;
  37332. this.collisionFound = true;
  37333. }
  37334. }
  37335. };
  37336. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  37337. for (var i = indexStart; i < indexEnd; i += 3) {
  37338. var p1 = pts[indices[i] - decal];
  37339. var p2 = pts[indices[i + 1] - decal];
  37340. var p3 = pts[indices[i + 2] - decal];
  37341. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  37342. }
  37343. };
  37344. Collider.prototype._getResponse = function (pos, vel) {
  37345. pos.addToRef(vel, this._destinationPoint);
  37346. vel.scaleInPlace((this.nearestDistance / vel.length()));
  37347. this.basePoint.addToRef(vel, pos);
  37348. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  37349. this._slidePlaneNormal.normalize();
  37350. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  37351. pos.addInPlace(this._displacementVector);
  37352. this.intersectionPoint.addInPlace(this._displacementVector);
  37353. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  37354. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  37355. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  37356. };
  37357. return Collider;
  37358. }());
  37359. BABYLON.Collider = Collider;
  37360. })(BABYLON || (BABYLON = {}));
  37361. //# sourceMappingURL=babylon.collider.js.map
  37362. var BABYLON;
  37363. (function (BABYLON) {
  37364. //WebWorker code will be inserted to this variable.
  37365. BABYLON.CollisionWorker = "";
  37366. var WorkerTaskType;
  37367. (function (WorkerTaskType) {
  37368. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  37369. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  37370. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  37371. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  37372. var WorkerReplyType;
  37373. (function (WorkerReplyType) {
  37374. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  37375. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  37376. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  37377. var CollisionCoordinatorWorker = (function () {
  37378. function CollisionCoordinatorWorker() {
  37379. var _this = this;
  37380. this._scaledPosition = BABYLON.Vector3.Zero();
  37381. this._scaledVelocity = BABYLON.Vector3.Zero();
  37382. this.onMeshUpdated = function (mesh) {
  37383. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  37384. };
  37385. this.onGeometryUpdated = function (geometry) {
  37386. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  37387. };
  37388. this._afterRender = function () {
  37389. if (!_this._init)
  37390. return;
  37391. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  37392. return;
  37393. }
  37394. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  37395. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  37396. if (_this._runningUpdated > 4) {
  37397. return;
  37398. }
  37399. ++_this._runningUpdated;
  37400. var payload = {
  37401. updatedMeshes: _this._addUpdateMeshesList,
  37402. updatedGeometries: _this._addUpdateGeometriesList,
  37403. removedGeometries: _this._toRemoveGeometryArray,
  37404. removedMeshes: _this._toRemoveMeshesArray
  37405. };
  37406. var message = {
  37407. payload: payload,
  37408. taskType: WorkerTaskType.UPDATE
  37409. };
  37410. var serializable = [];
  37411. for (var id in payload.updatedGeometries) {
  37412. if (payload.updatedGeometries.hasOwnProperty(id)) {
  37413. //prepare transferables
  37414. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  37415. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  37416. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  37417. }
  37418. }
  37419. _this._worker.postMessage(message, serializable);
  37420. _this._addUpdateMeshesList = {};
  37421. _this._addUpdateGeometriesList = {};
  37422. _this._toRemoveGeometryArray = [];
  37423. _this._toRemoveMeshesArray = [];
  37424. };
  37425. this._onMessageFromWorker = function (e) {
  37426. var returnData = e.data;
  37427. if (returnData.error != WorkerReplyType.SUCCESS) {
  37428. //TODO what errors can be returned from the worker?
  37429. BABYLON.Tools.Warn("error returned from worker!");
  37430. return;
  37431. }
  37432. switch (returnData.taskType) {
  37433. case WorkerTaskType.INIT:
  37434. _this._init = true;
  37435. //Update the worked with ALL of the scene's current state
  37436. _this._scene.meshes.forEach(function (mesh) {
  37437. _this.onMeshAdded(mesh);
  37438. });
  37439. _this._scene.getGeometries().forEach(function (geometry) {
  37440. _this.onGeometryAdded(geometry);
  37441. });
  37442. break;
  37443. case WorkerTaskType.UPDATE:
  37444. _this._runningUpdated--;
  37445. break;
  37446. case WorkerTaskType.COLLIDE:
  37447. _this._runningCollisionTask = false;
  37448. var returnPayload = returnData.payload;
  37449. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  37450. return;
  37451. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  37452. //cleanup
  37453. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  37454. break;
  37455. }
  37456. };
  37457. this._collisionsCallbackArray = [];
  37458. this._init = false;
  37459. this._runningUpdated = 0;
  37460. this._runningCollisionTask = false;
  37461. this._addUpdateMeshesList = {};
  37462. this._addUpdateGeometriesList = {};
  37463. this._toRemoveGeometryArray = [];
  37464. this._toRemoveMeshesArray = [];
  37465. }
  37466. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  37467. if (!this._init)
  37468. return;
  37469. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  37470. return;
  37471. position.divideToRef(collider.radius, this._scaledPosition);
  37472. velocity.divideToRef(collider.radius, this._scaledVelocity);
  37473. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  37474. var payload = {
  37475. collider: {
  37476. position: this._scaledPosition.asArray(),
  37477. velocity: this._scaledVelocity.asArray(),
  37478. radius: collider.radius.asArray()
  37479. },
  37480. collisionId: collisionIndex,
  37481. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  37482. maximumRetry: maximumRetry
  37483. };
  37484. var message = {
  37485. payload: payload,
  37486. taskType: WorkerTaskType.COLLIDE
  37487. };
  37488. this._worker.postMessage(message);
  37489. };
  37490. CollisionCoordinatorWorker.prototype.init = function (scene) {
  37491. this._scene = scene;
  37492. this._scene.registerAfterRender(this._afterRender);
  37493. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  37494. this._worker = new Worker(workerUrl);
  37495. this._worker.onmessage = this._onMessageFromWorker;
  37496. var message = {
  37497. payload: {},
  37498. taskType: WorkerTaskType.INIT
  37499. };
  37500. this._worker.postMessage(message);
  37501. };
  37502. CollisionCoordinatorWorker.prototype.destroy = function () {
  37503. this._scene.unregisterAfterRender(this._afterRender);
  37504. this._worker.terminate();
  37505. };
  37506. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  37507. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  37508. this.onMeshUpdated(mesh);
  37509. };
  37510. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  37511. this._toRemoveMeshesArray.push(mesh.uniqueId);
  37512. };
  37513. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  37514. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  37515. geometry.onGeometryUpdated = this.onGeometryUpdated;
  37516. this.onGeometryUpdated(geometry);
  37517. };
  37518. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  37519. this._toRemoveGeometryArray.push(geometry.id);
  37520. };
  37521. return CollisionCoordinatorWorker;
  37522. }());
  37523. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  37524. var submeshes = [];
  37525. if (mesh.subMeshes) {
  37526. submeshes = mesh.subMeshes.map(function (sm, idx) {
  37527. return {
  37528. position: idx,
  37529. verticesStart: sm.verticesStart,
  37530. verticesCount: sm.verticesCount,
  37531. indexStart: sm.indexStart,
  37532. indexCount: sm.indexCount,
  37533. hasMaterial: !!sm.getMaterial(),
  37534. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  37535. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  37536. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  37537. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  37538. };
  37539. });
  37540. }
  37541. var geometryId = null;
  37542. if (mesh instanceof BABYLON.Mesh) {
  37543. geometryId = mesh.geometry ? mesh.geometry.id : null;
  37544. }
  37545. else if (mesh instanceof BABYLON.InstancedMesh) {
  37546. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  37547. }
  37548. return {
  37549. uniqueId: mesh.uniqueId,
  37550. id: mesh.id,
  37551. name: mesh.name,
  37552. geometryId: geometryId,
  37553. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  37554. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  37555. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  37556. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  37557. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  37558. subMeshes: submeshes,
  37559. checkCollisions: mesh.checkCollisions
  37560. };
  37561. };
  37562. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  37563. return {
  37564. id: geometry.id,
  37565. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  37566. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  37567. indices: new Uint32Array(geometry.getIndices() || []),
  37568. };
  37569. };
  37570. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  37571. var CollisionCoordinatorLegacy = (function () {
  37572. function CollisionCoordinatorLegacy() {
  37573. this._scaledPosition = BABYLON.Vector3.Zero();
  37574. this._scaledVelocity = BABYLON.Vector3.Zero();
  37575. this._finalPosition = BABYLON.Vector3.Zero();
  37576. }
  37577. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  37578. position.divideToRef(collider.radius, this._scaledPosition);
  37579. velocity.divideToRef(collider.radius, this._scaledVelocity);
  37580. collider.collidedMesh = null;
  37581. collider.retry = 0;
  37582. collider.initialVelocity = this._scaledVelocity;
  37583. collider.initialPosition = this._scaledPosition;
  37584. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  37585. this._finalPosition.multiplyInPlace(collider.radius);
  37586. //run the callback
  37587. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  37588. };
  37589. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  37590. this._scene = scene;
  37591. };
  37592. CollisionCoordinatorLegacy.prototype.destroy = function () {
  37593. //Legacy need no destruction method.
  37594. };
  37595. //No update in legacy mode
  37596. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  37597. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  37598. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  37599. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  37600. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  37601. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  37602. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  37603. if (excludedMesh === void 0) { excludedMesh = null; }
  37604. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  37605. if (collider.retry >= maximumRetry) {
  37606. finalPosition.copyFrom(position);
  37607. return;
  37608. }
  37609. // Check if this is a mesh else camera or -1
  37610. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  37611. collider._initialize(position, velocity, closeDistance);
  37612. // Check all meshes
  37613. for (var index = 0; index < this._scene.meshes.length; index++) {
  37614. var mesh = this._scene.meshes[index];
  37615. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  37616. mesh._checkCollision(collider);
  37617. }
  37618. }
  37619. if (!collider.collisionFound) {
  37620. position.addToRef(velocity, finalPosition);
  37621. return;
  37622. }
  37623. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  37624. collider._getResponse(position, velocity);
  37625. }
  37626. if (velocity.length() <= closeDistance) {
  37627. finalPosition.copyFrom(position);
  37628. return;
  37629. }
  37630. collider.retry++;
  37631. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  37632. };
  37633. return CollisionCoordinatorLegacy;
  37634. }());
  37635. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  37636. })(BABYLON || (BABYLON = {}));
  37637. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  37638. var BABYLON;
  37639. (function (BABYLON) {
  37640. var Particle = (function () {
  37641. function Particle() {
  37642. this.position = BABYLON.Vector3.Zero();
  37643. this.direction = BABYLON.Vector3.Zero();
  37644. this.color = new BABYLON.Color4(0, 0, 0, 0);
  37645. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  37646. this.lifeTime = 1.0;
  37647. this.age = 0;
  37648. this.size = 0;
  37649. this.angle = 0;
  37650. this.angularSpeed = 0;
  37651. }
  37652. Particle.prototype.copyTo = function (other) {
  37653. other.position.copyFrom(this.position);
  37654. other.direction.copyFrom(this.direction);
  37655. other.color.copyFrom(this.color);
  37656. other.colorStep.copyFrom(this.colorStep);
  37657. other.lifeTime = this.lifeTime;
  37658. other.age = this.age;
  37659. other.size = this.size;
  37660. other.angle = this.angle;
  37661. other.angularSpeed = this.angularSpeed;
  37662. };
  37663. return Particle;
  37664. }());
  37665. BABYLON.Particle = Particle;
  37666. })(BABYLON || (BABYLON = {}));
  37667. //# sourceMappingURL=babylon.particle.js.map
  37668. var BABYLON;
  37669. (function (BABYLON) {
  37670. var randomNumber = function (min, max) {
  37671. if (min === max) {
  37672. return (min);
  37673. }
  37674. var random = Math.random();
  37675. return ((random * (max - min)) + min);
  37676. };
  37677. var ParticleSystem = (function () {
  37678. function ParticleSystem(name, capacity, scene, customEffect) {
  37679. var _this = this;
  37680. this.name = name;
  37681. // Members
  37682. this.animations = [];
  37683. this.renderingGroupId = 0;
  37684. this.emitter = null;
  37685. this.emitRate = 10;
  37686. this.manualEmitCount = -1;
  37687. this.updateSpeed = 0.01;
  37688. this.targetStopDuration = 0;
  37689. this.disposeOnStop = false;
  37690. this.minEmitPower = 1;
  37691. this.maxEmitPower = 1;
  37692. this.minLifeTime = 1;
  37693. this.maxLifeTime = 1;
  37694. this.minSize = 1;
  37695. this.maxSize = 1;
  37696. this.minAngularSpeed = 0;
  37697. this.maxAngularSpeed = 0;
  37698. this.layerMask = 0x0FFFFFFF;
  37699. this.customShader = null;
  37700. this.preventAutoStart = false;
  37701. /**
  37702. * An event triggered when the system is disposed.
  37703. * @type {BABYLON.Observable}
  37704. */
  37705. this.onDisposeObservable = new BABYLON.Observable();
  37706. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  37707. this.forceDepthWrite = false;
  37708. this.gravity = BABYLON.Vector3.Zero();
  37709. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  37710. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  37711. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  37712. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  37713. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37714. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37715. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  37716. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37717. this.particles = new Array();
  37718. this._stockParticles = new Array();
  37719. this._newPartsExcess = 0;
  37720. this._vertexBuffers = {};
  37721. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  37722. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  37723. this._scaledDirection = BABYLON.Vector3.Zero();
  37724. this._scaledGravity = BABYLON.Vector3.Zero();
  37725. this._currentRenderId = -1;
  37726. this._started = false;
  37727. this._stopped = false;
  37728. this._actualFrame = 0;
  37729. this.id = name;
  37730. this._capacity = capacity;
  37731. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  37732. this._customEffect = customEffect;
  37733. scene.particleSystems.push(this);
  37734. var indices = [];
  37735. var index = 0;
  37736. for (var count = 0; count < capacity; count++) {
  37737. indices.push(index);
  37738. indices.push(index + 1);
  37739. indices.push(index + 2);
  37740. indices.push(index);
  37741. indices.push(index + 2);
  37742. indices.push(index + 3);
  37743. index += 4;
  37744. }
  37745. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  37746. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  37747. this._vertexData = new Float32Array(capacity * 11 * 4);
  37748. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  37749. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  37750. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  37751. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  37752. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  37753. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  37754. this._vertexBuffers["options"] = options;
  37755. // Default behaviors
  37756. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  37757. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  37758. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  37759. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  37760. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  37761. };
  37762. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  37763. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  37764. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  37765. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  37766. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  37767. };
  37768. this.updateFunction = function (particles) {
  37769. for (var index = 0; index < particles.length; index++) {
  37770. var particle = particles[index];
  37771. particle.age += _this._scaledUpdateSpeed;
  37772. if (particle.age >= particle.lifeTime) {
  37773. _this.recycleParticle(particle);
  37774. index--;
  37775. continue;
  37776. }
  37777. else {
  37778. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  37779. particle.color.addInPlace(_this._scaledColorStep);
  37780. if (particle.color.a < 0)
  37781. particle.color.a = 0;
  37782. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  37783. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  37784. particle.position.addInPlace(_this._scaledDirection);
  37785. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  37786. particle.direction.addInPlace(_this._scaledGravity);
  37787. }
  37788. }
  37789. };
  37790. }
  37791. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  37792. set: function (callback) {
  37793. if (this._onDisposeObserver) {
  37794. this.onDisposeObservable.remove(this._onDisposeObserver);
  37795. }
  37796. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  37797. },
  37798. enumerable: true,
  37799. configurable: true
  37800. });
  37801. ParticleSystem.prototype.recycleParticle = function (particle) {
  37802. var lastParticle = this.particles.pop();
  37803. if (lastParticle !== particle) {
  37804. lastParticle.copyTo(particle);
  37805. this._stockParticles.push(lastParticle);
  37806. }
  37807. };
  37808. ParticleSystem.prototype.getCapacity = function () {
  37809. return this._capacity;
  37810. };
  37811. ParticleSystem.prototype.isAlive = function () {
  37812. return this._alive;
  37813. };
  37814. ParticleSystem.prototype.isStarted = function () {
  37815. return this._started;
  37816. };
  37817. ParticleSystem.prototype.start = function () {
  37818. this._started = true;
  37819. this._stopped = false;
  37820. this._actualFrame = 0;
  37821. };
  37822. ParticleSystem.prototype.stop = function () {
  37823. this._stopped = true;
  37824. };
  37825. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  37826. var offset = index * 11;
  37827. this._vertexData[offset] = particle.position.x;
  37828. this._vertexData[offset + 1] = particle.position.y;
  37829. this._vertexData[offset + 2] = particle.position.z;
  37830. this._vertexData[offset + 3] = particle.color.r;
  37831. this._vertexData[offset + 4] = particle.color.g;
  37832. this._vertexData[offset + 5] = particle.color.b;
  37833. this._vertexData[offset + 6] = particle.color.a;
  37834. this._vertexData[offset + 7] = particle.angle;
  37835. this._vertexData[offset + 8] = particle.size;
  37836. this._vertexData[offset + 9] = offsetX;
  37837. this._vertexData[offset + 10] = offsetY;
  37838. };
  37839. ParticleSystem.prototype._update = function (newParticles) {
  37840. // Update current
  37841. this._alive = this.particles.length > 0;
  37842. this.updateFunction(this.particles);
  37843. // Add new ones
  37844. var worldMatrix;
  37845. if (this.emitter.position) {
  37846. worldMatrix = this.emitter.getWorldMatrix();
  37847. }
  37848. else {
  37849. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  37850. }
  37851. var particle;
  37852. for (var index = 0; index < newParticles; index++) {
  37853. if (this.particles.length === this._capacity) {
  37854. break;
  37855. }
  37856. if (this._stockParticles.length !== 0) {
  37857. particle = this._stockParticles.pop();
  37858. particle.age = 0;
  37859. }
  37860. else {
  37861. particle = new BABYLON.Particle();
  37862. }
  37863. this.particles.push(particle);
  37864. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  37865. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  37866. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  37867. particle.size = randomNumber(this.minSize, this.maxSize);
  37868. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  37869. this.startPositionFunction(worldMatrix, particle.position, particle);
  37870. var step = randomNumber(0, 1.0);
  37871. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  37872. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  37873. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  37874. }
  37875. };
  37876. ParticleSystem.prototype._getEffect = function () {
  37877. if (this._customEffect) {
  37878. return this._customEffect;
  37879. }
  37880. ;
  37881. var defines = [];
  37882. if (this._scene.clipPlane) {
  37883. defines.push("#define CLIPPLANE");
  37884. }
  37885. // Effect
  37886. var join = defines.join("\n");
  37887. if (this._cachedDefines !== join) {
  37888. this._cachedDefines = join;
  37889. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  37890. }
  37891. return this._effect;
  37892. };
  37893. ParticleSystem.prototype.animate = function () {
  37894. if (!this._started)
  37895. return;
  37896. var effect = this._getEffect();
  37897. // Check
  37898. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  37899. return;
  37900. if (this._currentRenderId === this._scene.getRenderId()) {
  37901. return;
  37902. }
  37903. this._currentRenderId = this._scene.getRenderId();
  37904. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  37905. // determine the number of particles we need to create
  37906. var newParticles;
  37907. if (this.manualEmitCount > -1) {
  37908. newParticles = this.manualEmitCount;
  37909. this._newPartsExcess = 0;
  37910. this.manualEmitCount = 0;
  37911. }
  37912. else {
  37913. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  37914. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  37915. }
  37916. if (this._newPartsExcess > 1.0) {
  37917. newParticles += this._newPartsExcess >> 0;
  37918. this._newPartsExcess -= this._newPartsExcess >> 0;
  37919. }
  37920. this._alive = false;
  37921. if (!this._stopped) {
  37922. this._actualFrame += this._scaledUpdateSpeed;
  37923. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  37924. this.stop();
  37925. }
  37926. else {
  37927. newParticles = 0;
  37928. }
  37929. this._update(newParticles);
  37930. // Stopped?
  37931. if (this._stopped) {
  37932. if (!this._alive) {
  37933. this._started = false;
  37934. if (this.disposeOnStop) {
  37935. this._scene._toBeDisposed.push(this);
  37936. }
  37937. }
  37938. }
  37939. // Update VBO
  37940. var offset = 0;
  37941. for (var index = 0; index < this.particles.length; index++) {
  37942. var particle = this.particles[index];
  37943. this._appendParticleVertex(offset++, particle, 0, 0);
  37944. this._appendParticleVertex(offset++, particle, 1, 0);
  37945. this._appendParticleVertex(offset++, particle, 1, 1);
  37946. this._appendParticleVertex(offset++, particle, 0, 1);
  37947. }
  37948. this._vertexBuffer.update(this._vertexData);
  37949. };
  37950. ParticleSystem.prototype.render = function () {
  37951. var effect = this._getEffect();
  37952. // Check
  37953. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  37954. return 0;
  37955. var engine = this._scene.getEngine();
  37956. // Render
  37957. engine.enableEffect(effect);
  37958. engine.setState(false);
  37959. var viewMatrix = this._scene.getViewMatrix();
  37960. effect.setTexture("diffuseSampler", this.particleTexture);
  37961. effect.setMatrix("view", viewMatrix);
  37962. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  37963. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  37964. if (this._scene.clipPlane) {
  37965. var clipPlane = this._scene.clipPlane;
  37966. var invView = viewMatrix.clone();
  37967. invView.invert();
  37968. effect.setMatrix("invView", invView);
  37969. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  37970. }
  37971. // VBOs
  37972. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37973. // Draw order
  37974. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  37975. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  37976. }
  37977. else {
  37978. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  37979. }
  37980. if (this.forceDepthWrite) {
  37981. engine.setDepthWrite(true);
  37982. }
  37983. engine.draw(true, 0, this.particles.length * 6);
  37984. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37985. return this.particles.length;
  37986. };
  37987. ParticleSystem.prototype.dispose = function () {
  37988. if (this._vertexBuffer) {
  37989. this._vertexBuffer.dispose();
  37990. this._vertexBuffer = null;
  37991. }
  37992. if (this._indexBuffer) {
  37993. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37994. this._indexBuffer = null;
  37995. }
  37996. if (this.particleTexture) {
  37997. this.particleTexture.dispose();
  37998. this.particleTexture = null;
  37999. }
  38000. // Remove from scene
  38001. var index = this._scene.particleSystems.indexOf(this);
  38002. this._scene.particleSystems.splice(index, 1);
  38003. // Callback
  38004. this.onDisposeObservable.notifyObservers(this);
  38005. this.onDisposeObservable.clear();
  38006. };
  38007. // Clone
  38008. ParticleSystem.prototype.clone = function (name, newEmitter) {
  38009. var custom = null;
  38010. var program = null;
  38011. if (this.customShader != null) {
  38012. program = this.customShader;
  38013. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  38014. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  38015. }
  38016. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  38017. result.customShader = program;
  38018. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  38019. if (newEmitter === undefined) {
  38020. newEmitter = this.emitter;
  38021. }
  38022. result.emitter = newEmitter;
  38023. if (this.particleTexture) {
  38024. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  38025. }
  38026. if (!this.preventAutoStart) {
  38027. result.start();
  38028. }
  38029. return result;
  38030. };
  38031. ParticleSystem.prototype.serialize = function () {
  38032. var serializationObject = {};
  38033. serializationObject.name = this.name;
  38034. serializationObject.id = this.id;
  38035. // Emitter
  38036. if (this.emitter.position) {
  38037. serializationObject.emitterId = this.emitter.id;
  38038. }
  38039. else {
  38040. serializationObject.emitter = this.emitter.asArray();
  38041. }
  38042. serializationObject.capacity = this.getCapacity();
  38043. if (this.particleTexture) {
  38044. serializationObject.textureName = this.particleTexture.name;
  38045. }
  38046. // Animations
  38047. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  38048. // Particle system
  38049. serializationObject.minAngularSpeed = this.minAngularSpeed;
  38050. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  38051. serializationObject.minSize = this.minSize;
  38052. serializationObject.maxSize = this.maxSize;
  38053. serializationObject.minEmitPower = this.minEmitPower;
  38054. serializationObject.maxEmitPower = this.maxEmitPower;
  38055. serializationObject.minLifeTime = this.minLifeTime;
  38056. serializationObject.maxLifeTime = this.maxLifeTime;
  38057. serializationObject.emitRate = this.emitRate;
  38058. serializationObject.minEmitBox = this.minEmitBox.asArray();
  38059. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  38060. serializationObject.gravity = this.gravity.asArray();
  38061. serializationObject.direction1 = this.direction1.asArray();
  38062. serializationObject.direction2 = this.direction2.asArray();
  38063. serializationObject.color1 = this.color1.asArray();
  38064. serializationObject.color2 = this.color2.asArray();
  38065. serializationObject.colorDead = this.colorDead.asArray();
  38066. serializationObject.updateSpeed = this.updateSpeed;
  38067. serializationObject.targetStopDuration = this.targetStopDuration;
  38068. serializationObject.textureMask = this.textureMask.asArray();
  38069. serializationObject.blendMode = this.blendMode;
  38070. serializationObject.customShader = this.customShader;
  38071. serializationObject.preventAutoStart = this.preventAutoStart;
  38072. return serializationObject;
  38073. };
  38074. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  38075. var name = parsedParticleSystem.name;
  38076. var custom = null;
  38077. var program = null;
  38078. if (parsedParticleSystem.customShader) {
  38079. program = parsedParticleSystem.customShader;
  38080. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  38081. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  38082. }
  38083. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  38084. particleSystem.customShader = program;
  38085. if (parsedParticleSystem.id) {
  38086. particleSystem.id = parsedParticleSystem.id;
  38087. }
  38088. // Auto start
  38089. if (parsedParticleSystem.preventAutoStart) {
  38090. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  38091. }
  38092. // Texture
  38093. if (parsedParticleSystem.textureName) {
  38094. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  38095. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  38096. }
  38097. // Emitter
  38098. if (parsedParticleSystem.emitterId) {
  38099. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  38100. }
  38101. else {
  38102. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  38103. }
  38104. // Animations
  38105. if (parsedParticleSystem.animations) {
  38106. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  38107. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  38108. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  38109. }
  38110. }
  38111. if (parsedParticleSystem.autoAnimate) {
  38112. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  38113. }
  38114. // Particle system
  38115. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  38116. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  38117. particleSystem.minSize = parsedParticleSystem.minSize;
  38118. particleSystem.maxSize = parsedParticleSystem.maxSize;
  38119. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  38120. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  38121. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  38122. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  38123. particleSystem.emitRate = parsedParticleSystem.emitRate;
  38124. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  38125. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  38126. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  38127. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  38128. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  38129. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  38130. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  38131. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  38132. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  38133. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  38134. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  38135. particleSystem.blendMode = parsedParticleSystem.blendMode;
  38136. if (!particleSystem.preventAutoStart) {
  38137. particleSystem.start();
  38138. }
  38139. return particleSystem;
  38140. };
  38141. return ParticleSystem;
  38142. }());
  38143. // Statics
  38144. ParticleSystem.BLENDMODE_ONEONE = 0;
  38145. ParticleSystem.BLENDMODE_STANDARD = 1;
  38146. BABYLON.ParticleSystem = ParticleSystem;
  38147. })(BABYLON || (BABYLON = {}));
  38148. //# sourceMappingURL=babylon.particleSystem.js.map
  38149. var BABYLON;
  38150. (function (BABYLON) {
  38151. var SolidParticle = (function () {
  38152. /**
  38153. * Creates a Solid Particle object.
  38154. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  38155. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  38156. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  38157. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  38158. * `shapeId` (integer) is the model shape identifier in the SPS.
  38159. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  38160. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  38161. */
  38162. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  38163. this.idx = 0; // particle global index
  38164. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  38165. this.position = BABYLON.Vector3.Zero(); // position
  38166. this.rotation = BABYLON.Vector3.Zero(); // rotation
  38167. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  38168. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  38169. this.velocity = BABYLON.Vector3.Zero(); // velocity
  38170. this.alive = true; // alive
  38171. this.isVisible = true; // visibility
  38172. this._pos = 0; // index of this particle in the global "positions" array
  38173. this.shapeId = 0; // model shape id
  38174. this.idxInShape = 0; // index of the particle in its shape id
  38175. this.idx = particleIndex;
  38176. this._pos = positionIndex;
  38177. this._model = model;
  38178. this.shapeId = shapeId;
  38179. this.idxInShape = idxInShape;
  38180. this._sps = sps;
  38181. if (modelBoundingInfo) {
  38182. this._modelBoundingInfo = modelBoundingInfo;
  38183. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  38184. }
  38185. }
  38186. Object.defineProperty(SolidParticle.prototype, "scale", {
  38187. /**
  38188. * legacy support, changed scale to scaling
  38189. */
  38190. get: function () {
  38191. return this.scaling;
  38192. },
  38193. set: function (scale) {
  38194. this.scaling = scale;
  38195. },
  38196. enumerable: true,
  38197. configurable: true
  38198. });
  38199. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  38200. /**
  38201. * legacy support, changed quaternion to rotationQuaternion
  38202. */
  38203. get: function () {
  38204. return this.rotationQuaternion;
  38205. },
  38206. set: function (q) {
  38207. this.rotationQuaternion = q;
  38208. },
  38209. enumerable: true,
  38210. configurable: true
  38211. });
  38212. /**
  38213. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  38214. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  38215. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  38216. */
  38217. SolidParticle.prototype.intersectsMesh = function (target) {
  38218. if (!this._boundingInfo || !target._boundingInfo) {
  38219. return false;
  38220. }
  38221. if (this._sps._bSphereOnly) {
  38222. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  38223. }
  38224. return this._boundingInfo.intersects(target._boundingInfo, false);
  38225. };
  38226. return SolidParticle;
  38227. }());
  38228. BABYLON.SolidParticle = SolidParticle;
  38229. var ModelShape = (function () {
  38230. /**
  38231. * 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.
  38232. * SPS internal tool, don't use it manually.
  38233. */
  38234. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  38235. this.shapeID = id;
  38236. this._shape = shape;
  38237. this._shapeUV = shapeUV;
  38238. this._positionFunction = posFunction;
  38239. this._vertexFunction = vtxFunction;
  38240. }
  38241. return ModelShape;
  38242. }());
  38243. BABYLON.ModelShape = ModelShape;
  38244. })(BABYLON || (BABYLON = {}));
  38245. //# sourceMappingURL=babylon.solidParticle.js.map
  38246. var BABYLON;
  38247. (function (BABYLON) {
  38248. /**
  38249. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  38250. */
  38251. var SolidParticleSystem = (function () {
  38252. /**
  38253. * Creates a SPS (Solid Particle System) object.
  38254. * `name` (String) is the SPS name, this will be the underlying mesh name.
  38255. * `scene` (Scene) is the scene in which the SPS is added.
  38256. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  38257. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  38258. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  38259. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  38260. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  38261. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  38262. */
  38263. function SolidParticleSystem(name, scene, options) {
  38264. // public members
  38265. /**
  38266. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  38267. * Example : var p = SPS.particles[i];
  38268. */
  38269. this.particles = new Array();
  38270. /**
  38271. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  38272. */
  38273. this.nbParticles = 0;
  38274. /**
  38275. * If the particles must ever face the camera (default false). Useful for planar particles.
  38276. */
  38277. this.billboard = false;
  38278. /**
  38279. * Recompute normals when adding a shape
  38280. */
  38281. this.recomputeNormals = true;
  38282. /**
  38283. * This a counter ofr your own usage. It's not set by any SPS functions.
  38284. */
  38285. this.counter = 0;
  38286. /**
  38287. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  38288. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  38289. */
  38290. this.vars = {};
  38291. this._positions = new Array();
  38292. this._indices = new Array();
  38293. this._normals = new Array();
  38294. this._colors = new Array();
  38295. this._uvs = new Array();
  38296. this._index = 0; // indices index
  38297. this._updatable = true;
  38298. this._pickable = false;
  38299. this._isVisibilityBoxLocked = false;
  38300. this._alwaysVisible = false;
  38301. this._shapeCounter = 0;
  38302. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  38303. this._color = new BABYLON.Color4(0, 0, 0, 0);
  38304. this._computeParticleColor = true;
  38305. this._computeParticleTexture = true;
  38306. this._computeParticleRotation = true;
  38307. this._computeParticleVertex = false;
  38308. this._computeBoundingBox = false;
  38309. this._cam_axisZ = BABYLON.Vector3.Zero();
  38310. this._cam_axisY = BABYLON.Vector3.Zero();
  38311. this._cam_axisX = BABYLON.Vector3.Zero();
  38312. this._axisX = BABYLON.Axis.X;
  38313. this._axisY = BABYLON.Axis.Y;
  38314. this._axisZ = BABYLON.Axis.Z;
  38315. this._camDir = BABYLON.Vector3.Zero();
  38316. this._rotMatrix = new BABYLON.Matrix();
  38317. this._invertMatrix = new BABYLON.Matrix();
  38318. this._rotated = BABYLON.Vector3.Zero();
  38319. this._quaternion = new BABYLON.Quaternion();
  38320. this._vertex = BABYLON.Vector3.Zero();
  38321. this._normal = BABYLON.Vector3.Zero();
  38322. this._yaw = 0.0;
  38323. this._pitch = 0.0;
  38324. this._roll = 0.0;
  38325. this._halfroll = 0.0;
  38326. this._halfpitch = 0.0;
  38327. this._halfyaw = 0.0;
  38328. this._sinRoll = 0.0;
  38329. this._cosRoll = 0.0;
  38330. this._sinPitch = 0.0;
  38331. this._cosPitch = 0.0;
  38332. this._sinYaw = 0.0;
  38333. this._cosYaw = 0.0;
  38334. this._w = 0.0;
  38335. this._mustUnrotateFixedNormals = false;
  38336. this._minimum = BABYLON.Tmp.Vector3[0];
  38337. this._maximum = BABYLON.Tmp.Vector3[1];
  38338. this._scale = BABYLON.Tmp.Vector3[2];
  38339. this._translation = BABYLON.Tmp.Vector3[3];
  38340. this._minBbox = BABYLON.Tmp.Vector3[4];
  38341. this._maxBbox = BABYLON.Tmp.Vector3[5];
  38342. this._particlesIntersect = false;
  38343. this._bSphereOnly = false;
  38344. this._bSphereRadiusFactor = 1.0;
  38345. this.name = name;
  38346. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38347. this._camera = scene.activeCamera;
  38348. this._pickable = options ? options.isPickable : false;
  38349. this._particlesIntersect = options ? options.particleIntersection : false;
  38350. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  38351. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  38352. if (options && options.updatable) {
  38353. this._updatable = options.updatable;
  38354. }
  38355. else {
  38356. this._updatable = true;
  38357. }
  38358. if (this._pickable) {
  38359. this.pickedParticles = [];
  38360. }
  38361. }
  38362. /**
  38363. * Builds the SPS underlying mesh. Returns a standard Mesh.
  38364. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  38365. */
  38366. SolidParticleSystem.prototype.buildMesh = function () {
  38367. if (this.nbParticles === 0) {
  38368. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  38369. this.addShape(triangle, 1);
  38370. triangle.dispose();
  38371. }
  38372. this._positions32 = new Float32Array(this._positions);
  38373. this._uvs32 = new Float32Array(this._uvs);
  38374. this._colors32 = new Float32Array(this._colors);
  38375. if (this.recomputeNormals) {
  38376. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  38377. }
  38378. this._normals32 = new Float32Array(this._normals);
  38379. this._fixedNormal32 = new Float32Array(this._normals);
  38380. if (this._mustUnrotateFixedNormals) {
  38381. this._unrotateFixedNormals();
  38382. }
  38383. var vertexData = new BABYLON.VertexData();
  38384. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  38385. vertexData.indices = this._indices;
  38386. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  38387. if (this._uvs32) {
  38388. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  38389. ;
  38390. }
  38391. if (this._colors32) {
  38392. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  38393. }
  38394. var mesh = new BABYLON.Mesh(this.name, this._scene);
  38395. vertexData.applyToMesh(mesh, this._updatable);
  38396. this.mesh = mesh;
  38397. this.mesh.isPickable = this._pickable;
  38398. // free memory
  38399. this._positions = null;
  38400. this._normals = null;
  38401. this._uvs = null;
  38402. this._colors = null;
  38403. if (!this._updatable) {
  38404. this.particles.length = 0;
  38405. }
  38406. return mesh;
  38407. };
  38408. /**
  38409. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  38410. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  38411. * Thus the particles generated from `digest()` have their property `position` set yet.
  38412. * `mesh` ( Mesh ) is the mesh to be digested
  38413. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  38414. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  38415. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  38416. */
  38417. SolidParticleSystem.prototype.digest = function (mesh, options) {
  38418. var size = (options && options.facetNb) || 1;
  38419. var number = (options && options.number);
  38420. var delta = (options && options.delta) || 0;
  38421. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38422. var meshInd = mesh.getIndices();
  38423. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38424. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38425. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38426. var f = 0; // facet counter
  38427. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  38428. // compute size from number
  38429. if (number) {
  38430. number = (number > totalFacets) ? totalFacets : number;
  38431. size = Math.round(totalFacets / number);
  38432. delta = 0;
  38433. }
  38434. else {
  38435. size = (size > totalFacets) ? totalFacets : size;
  38436. }
  38437. var facetPos = []; // submesh positions
  38438. var facetInd = []; // submesh indices
  38439. var facetUV = []; // submesh UV
  38440. var facetCol = []; // submesh colors
  38441. var barycenter = BABYLON.Tmp.Vector3[0];
  38442. var rand;
  38443. var sizeO = size;
  38444. while (f < totalFacets) {
  38445. size = sizeO + Math.floor((1 + delta) * Math.random());
  38446. if (f > totalFacets - size) {
  38447. size = totalFacets - f;
  38448. }
  38449. // reset temp arrays
  38450. facetPos.length = 0;
  38451. facetInd.length = 0;
  38452. facetUV.length = 0;
  38453. facetCol.length = 0;
  38454. // iterate over "size" facets
  38455. var fi = 0;
  38456. for (var j = f * 3; j < (f + size) * 3; j++) {
  38457. facetInd.push(fi);
  38458. var i = meshInd[j];
  38459. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  38460. if (meshUV) {
  38461. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  38462. }
  38463. if (meshCol) {
  38464. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  38465. }
  38466. fi++;
  38467. }
  38468. // create a model shape for each single particle
  38469. var idx = this.nbParticles;
  38470. var shape = this._posToShape(facetPos);
  38471. var shapeUV = this._uvsToShapeUV(facetUV);
  38472. // compute the barycenter of the shape
  38473. var v;
  38474. for (v = 0; v < shape.length; v++) {
  38475. barycenter.addInPlace(shape[v]);
  38476. }
  38477. barycenter.scaleInPlace(1 / shape.length);
  38478. // shift the shape from its barycenter to the origin
  38479. for (v = 0; v < shape.length; v++) {
  38480. shape[v].subtractInPlace(barycenter);
  38481. }
  38482. var bInfo;
  38483. if (this._particlesIntersect) {
  38484. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  38485. }
  38486. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  38487. // add the particle in the SPS
  38488. var currentPos = this._positions.length;
  38489. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  38490. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  38491. // initialize the particle position
  38492. this.particles[this.nbParticles].position.addInPlace(barycenter);
  38493. this._index += shape.length;
  38494. idx++;
  38495. this.nbParticles++;
  38496. this._shapeCounter++;
  38497. f += size;
  38498. }
  38499. return this;
  38500. };
  38501. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  38502. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  38503. var index = 0;
  38504. var idx = 0;
  38505. for (var p = 0; p < this.particles.length; p++) {
  38506. this._particle = this.particles[p];
  38507. this._shape = this._particle._model._shape;
  38508. if (this._particle.rotationQuaternion) {
  38509. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  38510. }
  38511. else {
  38512. this._yaw = this._particle.rotation.y;
  38513. this._pitch = this._particle.rotation.x;
  38514. this._roll = this._particle.rotation.z;
  38515. this._quaternionRotationYPR();
  38516. }
  38517. this._quaternionToRotationMatrix();
  38518. this._rotMatrix.invertToRef(this._invertMatrix);
  38519. for (var pt = 0; pt < this._shape.length; pt++) {
  38520. idx = index + pt * 3;
  38521. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  38522. this._fixedNormal32[idx] = this._normal.x;
  38523. this._fixedNormal32[idx + 1] = this._normal.y;
  38524. this._fixedNormal32[idx + 2] = this._normal.z;
  38525. }
  38526. index = idx + 3;
  38527. }
  38528. };
  38529. //reset copy
  38530. SolidParticleSystem.prototype._resetCopy = function () {
  38531. this._copy.position.x = 0;
  38532. this._copy.position.y = 0;
  38533. this._copy.position.z = 0;
  38534. this._copy.rotation.x = 0;
  38535. this._copy.rotation.y = 0;
  38536. this._copy.rotation.z = 0;
  38537. this._copy.rotationQuaternion = null;
  38538. this._copy.scaling.x = 1;
  38539. this._copy.scaling.y = 1;
  38540. this._copy.scaling.z = 1;
  38541. this._copy.uvs.x = 0;
  38542. this._copy.uvs.y = 0;
  38543. this._copy.uvs.z = 1;
  38544. this._copy.uvs.w = 1;
  38545. this._copy.color = null;
  38546. };
  38547. // _meshBuilder : inserts the shape model in the global SPS mesh
  38548. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  38549. var i;
  38550. var u = 0;
  38551. var c = 0;
  38552. var n = 0;
  38553. this._resetCopy();
  38554. if (options && options.positionFunction) {
  38555. options.positionFunction(this._copy, idx, idxInShape);
  38556. this._mustUnrotateFixedNormals = true;
  38557. }
  38558. if (this._copy.rotationQuaternion) {
  38559. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  38560. }
  38561. else {
  38562. this._yaw = this._copy.rotation.y;
  38563. this._pitch = this._copy.rotation.x;
  38564. this._roll = this._copy.rotation.z;
  38565. this._quaternionRotationYPR();
  38566. }
  38567. this._quaternionToRotationMatrix();
  38568. for (i = 0; i < shape.length; i++) {
  38569. this._vertex.x = shape[i].x;
  38570. this._vertex.y = shape[i].y;
  38571. this._vertex.z = shape[i].z;
  38572. if (options && options.vertexFunction) {
  38573. options.vertexFunction(this._copy, this._vertex, i);
  38574. }
  38575. this._vertex.x *= this._copy.scaling.x;
  38576. this._vertex.y *= this._copy.scaling.y;
  38577. this._vertex.z *= this._copy.scaling.z;
  38578. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38579. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  38580. if (meshUV) {
  38581. 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);
  38582. u += 2;
  38583. }
  38584. if (this._copy.color) {
  38585. this._color = this._copy.color;
  38586. }
  38587. else if (meshCol && meshCol[c] !== undefined) {
  38588. this._color.r = meshCol[c];
  38589. this._color.g = meshCol[c + 1];
  38590. this._color.b = meshCol[c + 2];
  38591. this._color.a = meshCol[c + 3];
  38592. }
  38593. else {
  38594. this._color.r = 1;
  38595. this._color.g = 1;
  38596. this._color.b = 1;
  38597. this._color.a = 1;
  38598. }
  38599. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  38600. c += 4;
  38601. if (!this.recomputeNormals && meshNor) {
  38602. this._normal.x = meshNor[n];
  38603. this._normal.y = meshNor[n + 1];
  38604. this._normal.z = meshNor[n + 2];
  38605. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  38606. normals.push(this._normal.x, this._normal.y, this._normal.z);
  38607. n += 3;
  38608. }
  38609. }
  38610. for (i = 0; i < meshInd.length; i++) {
  38611. indices.push(p + meshInd[i]);
  38612. }
  38613. if (this._pickable) {
  38614. var nbfaces = meshInd.length / 3;
  38615. for (i = 0; i < nbfaces; i++) {
  38616. this.pickedParticles.push({ idx: idx, faceId: i });
  38617. }
  38618. }
  38619. return this._copy;
  38620. };
  38621. // returns a shape array from positions array
  38622. SolidParticleSystem.prototype._posToShape = function (positions) {
  38623. var shape = [];
  38624. for (var i = 0; i < positions.length; i += 3) {
  38625. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  38626. }
  38627. return shape;
  38628. };
  38629. // returns a shapeUV array from a Vector4 uvs
  38630. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  38631. var shapeUV = [];
  38632. if (uvs) {
  38633. for (var i = 0; i < uvs.length; i++)
  38634. shapeUV.push(uvs[i]);
  38635. }
  38636. return shapeUV;
  38637. };
  38638. // adds a new particle object in the particles array
  38639. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  38640. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  38641. this.particles.push(sp);
  38642. return sp;
  38643. };
  38644. /**
  38645. * Adds some particles to the SPS from the model shape. Returns the shape id.
  38646. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  38647. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  38648. * `nb` (positive integer) the number of particles to be created from this model
  38649. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  38650. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  38651. */
  38652. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  38653. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38654. var meshInd = mesh.getIndices();
  38655. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38656. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38657. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38658. var bbInfo;
  38659. if (this._particlesIntersect) {
  38660. bbInfo = mesh.getBoundingInfo();
  38661. }
  38662. var shape = this._posToShape(meshPos);
  38663. var shapeUV = this._uvsToShapeUV(meshUV);
  38664. var posfunc = options ? options.positionFunction : null;
  38665. var vtxfunc = options ? options.vertexFunction : null;
  38666. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  38667. // particles
  38668. var sp;
  38669. var currentCopy;
  38670. var idx = this.nbParticles;
  38671. for (var i = 0; i < nb; i++) {
  38672. var currentPos = this._positions.length;
  38673. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  38674. if (this._updatable) {
  38675. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  38676. sp.position.copyFrom(currentCopy.position);
  38677. sp.rotation.copyFrom(currentCopy.rotation);
  38678. if (currentCopy.rotationQuaternion) {
  38679. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  38680. }
  38681. if (currentCopy.color) {
  38682. sp.color.copyFrom(currentCopy.color);
  38683. }
  38684. sp.scaling.copyFrom(currentCopy.scaling);
  38685. sp.uvs.copyFrom(currentCopy.uvs);
  38686. }
  38687. this._index += shape.length;
  38688. idx++;
  38689. }
  38690. this.nbParticles += nb;
  38691. this._shapeCounter++;
  38692. return this._shapeCounter - 1;
  38693. };
  38694. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  38695. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  38696. this._resetCopy();
  38697. if (particle._model._positionFunction) {
  38698. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  38699. }
  38700. if (this._copy.rotationQuaternion) {
  38701. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  38702. }
  38703. else {
  38704. this._yaw = this._copy.rotation.y;
  38705. this._pitch = this._copy.rotation.x;
  38706. this._roll = this._copy.rotation.z;
  38707. this._quaternionRotationYPR();
  38708. }
  38709. this._quaternionToRotationMatrix();
  38710. this._shape = particle._model._shape;
  38711. for (var pt = 0; pt < this._shape.length; pt++) {
  38712. this._vertex.x = this._shape[pt].x;
  38713. this._vertex.y = this._shape[pt].y;
  38714. this._vertex.z = this._shape[pt].z;
  38715. if (particle._model._vertexFunction) {
  38716. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  38717. }
  38718. this._vertex.x *= this._copy.scaling.x;
  38719. this._vertex.y *= this._copy.scaling.y;
  38720. this._vertex.z *= this._copy.scaling.z;
  38721. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38722. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  38723. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  38724. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  38725. }
  38726. particle.position.x = 0.0;
  38727. particle.position.y = 0.0;
  38728. particle.position.z = 0.0;
  38729. particle.rotation.x = 0.0;
  38730. particle.rotation.y = 0.0;
  38731. particle.rotation.z = 0.0;
  38732. particle.rotationQuaternion = null;
  38733. particle.scaling.x = 1.0;
  38734. particle.scaling.y = 1.0;
  38735. particle.scaling.z = 1.0;
  38736. };
  38737. /**
  38738. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  38739. * Returns the SPS.
  38740. */
  38741. SolidParticleSystem.prototype.rebuildMesh = function () {
  38742. for (var p = 0; p < this.particles.length; p++) {
  38743. this._rebuildParticle(this.particles[p]);
  38744. }
  38745. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38746. return this;
  38747. };
  38748. /**
  38749. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  38750. * This method calls `updateParticle()` for each particle of the SPS.
  38751. * For an animated SPS, it is usually called within the render loop.
  38752. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  38753. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  38754. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  38755. * Returns the SPS.
  38756. */
  38757. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  38758. if (start === void 0) { start = 0; }
  38759. if (end === void 0) { end = this.nbParticles - 1; }
  38760. if (update === void 0) { update = true; }
  38761. if (!this._updatable) {
  38762. return;
  38763. }
  38764. // custom beforeUpdate
  38765. this.beforeUpdateParticles(start, end, update);
  38766. this._cam_axisX.x = 1.0;
  38767. this._cam_axisX.y = 0.0;
  38768. this._cam_axisX.z = 0.0;
  38769. this._cam_axisY.x = 0.0;
  38770. this._cam_axisY.y = 1.0;
  38771. this._cam_axisY.z = 0.0;
  38772. this._cam_axisZ.x = 0.0;
  38773. this._cam_axisZ.y = 0.0;
  38774. this._cam_axisZ.z = 1.0;
  38775. // if the particles will always face the camera
  38776. if (this.billboard) {
  38777. this.mesh.computeWorldMatrix(true);
  38778. // compute the camera position and un-rotate it by the current mesh rotation
  38779. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  38780. this._quaternionToRotationMatrix();
  38781. this._rotMatrix.invertToRef(this._invertMatrix);
  38782. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  38783. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  38784. this._cam_axisZ.normalize();
  38785. // same for camera up vector extracted from the cam view matrix
  38786. var view = this._camera.getViewMatrix(true);
  38787. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  38788. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  38789. this._cam_axisY.normalize();
  38790. this._cam_axisX.normalize();
  38791. }
  38792. }
  38793. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  38794. var idx = 0; // current position index in the global array positions32
  38795. var index = 0; // position start index in the global array positions32 of the current particle
  38796. var colidx = 0; // current color index in the global array colors32
  38797. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  38798. var uvidx = 0; // current uv index in the global array uvs32
  38799. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  38800. var pt = 0; // current index in the particle model shape
  38801. if (this.mesh.isFacetDataEnabled) {
  38802. this._computeBoundingBox = true;
  38803. }
  38804. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  38805. if (this._computeBoundingBox) {
  38806. if (start == 0 && end == this.nbParticles - 1) {
  38807. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  38808. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  38809. }
  38810. else {
  38811. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  38812. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  38813. }
  38814. }
  38815. // particle loop
  38816. index = this.particles[start]._pos;
  38817. var vpos = (index / 3) | 0;
  38818. colorIndex = vpos * 4;
  38819. uvIndex = vpos * 2;
  38820. for (var p = start; p <= end; p++) {
  38821. this._particle = this.particles[p];
  38822. this._shape = this._particle._model._shape;
  38823. this._shapeUV = this._particle._model._shapeUV;
  38824. // call to custom user function to update the particle properties
  38825. this.updateParticle(this._particle);
  38826. if (this._particle.isVisible) {
  38827. // particle rotation matrix
  38828. if (this.billboard) {
  38829. this._particle.rotation.x = 0.0;
  38830. this._particle.rotation.y = 0.0;
  38831. }
  38832. if (this._computeParticleRotation || this.billboard) {
  38833. if (this._particle.rotationQuaternion) {
  38834. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  38835. }
  38836. else {
  38837. this._yaw = this._particle.rotation.y;
  38838. this._pitch = this._particle.rotation.x;
  38839. this._roll = this._particle.rotation.z;
  38840. this._quaternionRotationYPR();
  38841. }
  38842. this._quaternionToRotationMatrix();
  38843. }
  38844. // particle vertex loop
  38845. for (pt = 0; pt < this._shape.length; pt++) {
  38846. idx = index + pt * 3;
  38847. colidx = colorIndex + pt * 4;
  38848. uvidx = uvIndex + pt * 2;
  38849. this._vertex.x = this._shape[pt].x;
  38850. this._vertex.y = this._shape[pt].y;
  38851. this._vertex.z = this._shape[pt].z;
  38852. if (this._computeParticleVertex) {
  38853. this.updateParticleVertex(this._particle, this._vertex, pt);
  38854. }
  38855. // positions
  38856. this._vertex.x *= this._particle.scaling.x;
  38857. this._vertex.y *= this._particle.scaling.y;
  38858. this._vertex.z *= this._particle.scaling.z;
  38859. 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];
  38860. 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;
  38861. 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;
  38862. 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;
  38863. 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;
  38864. 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;
  38865. 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;
  38866. if (this._computeBoundingBox) {
  38867. if (this._positions32[idx] < this._minimum.x) {
  38868. this._minimum.x = this._positions32[idx];
  38869. }
  38870. if (this._positions32[idx] > this._maximum.x) {
  38871. this._maximum.x = this._positions32[idx];
  38872. }
  38873. if (this._positions32[idx + 1] < this._minimum.y) {
  38874. this._minimum.y = this._positions32[idx + 1];
  38875. }
  38876. if (this._positions32[idx + 1] > this._maximum.y) {
  38877. this._maximum.y = this._positions32[idx + 1];
  38878. }
  38879. if (this._positions32[idx + 2] < this._minimum.z) {
  38880. this._minimum.z = this._positions32[idx + 2];
  38881. }
  38882. if (this._positions32[idx + 2] > this._maximum.z) {
  38883. this._maximum.z = this._positions32[idx + 2];
  38884. }
  38885. }
  38886. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  38887. if (!this._computeParticleVertex) {
  38888. this._normal.x = this._fixedNormal32[idx];
  38889. this._normal.y = this._fixedNormal32[idx + 1];
  38890. this._normal.z = this._fixedNormal32[idx + 2];
  38891. 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]);
  38892. 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]);
  38893. 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]);
  38894. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  38895. 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;
  38896. 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;
  38897. }
  38898. if (this._computeParticleColor) {
  38899. this._colors32[colidx] = this._particle.color.r;
  38900. this._colors32[colidx + 1] = this._particle.color.g;
  38901. this._colors32[colidx + 2] = this._particle.color.b;
  38902. this._colors32[colidx + 3] = this._particle.color.a;
  38903. }
  38904. if (this._computeParticleTexture) {
  38905. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38906. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38907. }
  38908. }
  38909. }
  38910. else {
  38911. for (pt = 0; pt < this._shape.length; pt++) {
  38912. idx = index + pt * 3;
  38913. colidx = colorIndex + pt * 4;
  38914. uvidx = uvIndex + pt * 2;
  38915. this._positions32[idx] = this._camera.position.x;
  38916. this._positions32[idx + 1] = this._camera.position.y;
  38917. this._positions32[idx + 2] = this._camera.position.z;
  38918. this._normals32[idx] = 0.0;
  38919. this._normals32[idx + 1] = 0.0;
  38920. this._normals32[idx + 2] = 0.0;
  38921. if (this._computeParticleColor) {
  38922. this._colors32[colidx] = this._particle.color.r;
  38923. this._colors32[colidx + 1] = this._particle.color.g;
  38924. this._colors32[colidx + 2] = this._particle.color.b;
  38925. this._colors32[colidx + 3] = this._particle.color.a;
  38926. }
  38927. if (this._computeParticleTexture) {
  38928. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38929. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38930. }
  38931. }
  38932. }
  38933. // if the particle intersections must be computed : update the bbInfo
  38934. if (this._particlesIntersect) {
  38935. var bInfo = this._particle._boundingInfo;
  38936. var bBox = bInfo.boundingBox;
  38937. var bSphere = bInfo.boundingSphere;
  38938. if (!this._bSphereOnly) {
  38939. // place, scale and rotate the particle bbox within the SPS local system, then update it
  38940. for (var b = 0; b < bBox.vectors.length; b++) {
  38941. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  38942. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  38943. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  38944. 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];
  38945. 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;
  38946. 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;
  38947. 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;
  38948. 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;
  38949. 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;
  38950. 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;
  38951. }
  38952. bBox._update(this.mesh._worldMatrix);
  38953. }
  38954. // place and scale the particle bouding sphere in the SPS local system, then update it
  38955. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  38956. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  38957. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  38958. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  38959. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  38960. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  38961. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  38962. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  38963. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  38964. 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));
  38965. bSphere._update(this.mesh._worldMatrix);
  38966. }
  38967. // increment indexes for the next particle
  38968. index = idx + 3;
  38969. colorIndex = colidx + 4;
  38970. uvIndex = uvidx + 2;
  38971. }
  38972. // if the VBO must be updated
  38973. if (update) {
  38974. if (this._computeParticleColor) {
  38975. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  38976. }
  38977. if (this._computeParticleTexture) {
  38978. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  38979. }
  38980. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38981. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  38982. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  38983. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  38984. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  38985. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  38986. for (var i = 0; i < this._normals32.length; i++) {
  38987. this._fixedNormal32[i] = this._normals32[i];
  38988. }
  38989. }
  38990. if (!this.mesh.areNormalsFrozen) {
  38991. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  38992. }
  38993. }
  38994. }
  38995. if (this._computeBoundingBox) {
  38996. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  38997. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  38998. }
  38999. this.afterUpdateParticles(start, end, update);
  39000. return this;
  39001. };
  39002. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  39003. this._halfroll = this._roll * 0.5;
  39004. this._halfpitch = this._pitch * 0.5;
  39005. this._halfyaw = this._yaw * 0.5;
  39006. this._sinRoll = Math.sin(this._halfroll);
  39007. this._cosRoll = Math.cos(this._halfroll);
  39008. this._sinPitch = Math.sin(this._halfpitch);
  39009. this._cosPitch = Math.cos(this._halfpitch);
  39010. this._sinYaw = Math.sin(this._halfyaw);
  39011. this._cosYaw = Math.cos(this._halfyaw);
  39012. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  39013. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  39014. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  39015. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  39016. };
  39017. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  39018. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  39019. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  39020. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  39021. this._rotMatrix.m[3] = 0;
  39022. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  39023. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  39024. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  39025. this._rotMatrix.m[7] = 0;
  39026. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  39027. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  39028. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  39029. this._rotMatrix.m[11] = 0;
  39030. this._rotMatrix.m[12] = 0;
  39031. this._rotMatrix.m[13] = 0;
  39032. this._rotMatrix.m[14] = 0;
  39033. this._rotMatrix.m[15] = 1.0;
  39034. };
  39035. /**
  39036. * Disposes the SPS.
  39037. * Returns nothing.
  39038. */
  39039. SolidParticleSystem.prototype.dispose = function () {
  39040. this.mesh.dispose();
  39041. this.vars = null;
  39042. // drop references to internal big arrays for the GC
  39043. this._positions = null;
  39044. this._indices = null;
  39045. this._normals = null;
  39046. this._uvs = null;
  39047. this._colors = null;
  39048. this._positions32 = null;
  39049. this._normals32 = null;
  39050. this._fixedNormal32 = null;
  39051. this._uvs32 = null;
  39052. this._colors32 = null;
  39053. this.pickedParticles = null;
  39054. };
  39055. /**
  39056. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  39057. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39058. * Returns the SPS.
  39059. */
  39060. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  39061. if (!this._isVisibilityBoxLocked) {
  39062. this.mesh.refreshBoundingInfo();
  39063. }
  39064. return this;
  39065. };
  39066. /**
  39067. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  39068. * @param size the size (float) of the visibility box
  39069. * note : this doesn't lock the SPS mesh bounding box.
  39070. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39071. */
  39072. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  39073. var vis = size / 2;
  39074. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  39075. };
  39076. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  39077. // getter and setter
  39078. get: function () {
  39079. return this._alwaysVisible;
  39080. },
  39081. /**
  39082. * Sets the SPS as always visible or not
  39083. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39084. */
  39085. set: function (val) {
  39086. this._alwaysVisible = val;
  39087. this.mesh.alwaysSelectAsActiveMesh = val;
  39088. },
  39089. enumerable: true,
  39090. configurable: true
  39091. });
  39092. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  39093. get: function () {
  39094. return this._isVisibilityBoxLocked;
  39095. },
  39096. /**
  39097. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  39098. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39099. */
  39100. set: function (val) {
  39101. this._isVisibilityBoxLocked = val;
  39102. this.mesh.getBoundingInfo().isLocked = val;
  39103. },
  39104. enumerable: true,
  39105. configurable: true
  39106. });
  39107. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  39108. // getters
  39109. get: function () {
  39110. return this._computeParticleRotation;
  39111. },
  39112. // Optimizer setters
  39113. /**
  39114. * Tells to `setParticles()` to compute the particle rotations or not.
  39115. * Default value : true. The SPS is faster when it's set to false.
  39116. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  39117. */
  39118. set: function (val) {
  39119. this._computeParticleRotation = val;
  39120. },
  39121. enumerable: true,
  39122. configurable: true
  39123. });
  39124. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  39125. get: function () {
  39126. return this._computeParticleColor;
  39127. },
  39128. /**
  39129. * Tells to `setParticles()` to compute the particle colors or not.
  39130. * Default value : true. The SPS is faster when it's set to false.
  39131. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  39132. */
  39133. set: function (val) {
  39134. this._computeParticleColor = val;
  39135. },
  39136. enumerable: true,
  39137. configurable: true
  39138. });
  39139. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  39140. get: function () {
  39141. return this._computeParticleTexture;
  39142. },
  39143. /**
  39144. * Tells to `setParticles()` to compute the particle textures or not.
  39145. * Default value : true. The SPS is faster when it's set to false.
  39146. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  39147. */
  39148. set: function (val) {
  39149. this._computeParticleTexture = val;
  39150. },
  39151. enumerable: true,
  39152. configurable: true
  39153. });
  39154. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  39155. get: function () {
  39156. return this._computeParticleVertex;
  39157. },
  39158. /**
  39159. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  39160. * Default value : false. The SPS is faster when it's set to false.
  39161. * Note : the particle custom vertex positions aren't stored values.
  39162. */
  39163. set: function (val) {
  39164. this._computeParticleVertex = val;
  39165. },
  39166. enumerable: true,
  39167. configurable: true
  39168. });
  39169. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  39170. get: function () {
  39171. return this._computeBoundingBox;
  39172. },
  39173. /**
  39174. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  39175. */
  39176. set: function (val) {
  39177. this._computeBoundingBox = val;
  39178. },
  39179. enumerable: true,
  39180. configurable: true
  39181. });
  39182. // =======================================================================
  39183. // Particle behavior logic
  39184. // these following methods may be overwritten by the user to fit his needs
  39185. /**
  39186. * This function does nothing. It may be overwritten to set all the particle first values.
  39187. * The SPS doesn't call this function, you may have to call it by your own.
  39188. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39189. */
  39190. SolidParticleSystem.prototype.initParticles = function () {
  39191. };
  39192. /**
  39193. * This function does nothing. It may be overwritten to recycle a particle.
  39194. * The SPS doesn't call this function, you may have to call it by your own.
  39195. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39196. */
  39197. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  39198. return particle;
  39199. };
  39200. /**
  39201. * Updates a particle : this function should be overwritten by the user.
  39202. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  39203. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39204. * ex : just set a particle position or velocity and recycle conditions
  39205. */
  39206. SolidParticleSystem.prototype.updateParticle = function (particle) {
  39207. return particle;
  39208. };
  39209. /**
  39210. * Updates a vertex of a particle : it can be overwritten by the user.
  39211. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  39212. * @param particle the current particle
  39213. * @param vertex the current index of the current particle
  39214. * @param pt the index of the current vertex in the particle shape
  39215. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  39216. * ex : just set a vertex particle position
  39217. */
  39218. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  39219. return vertex;
  39220. };
  39221. /**
  39222. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  39223. * This does nothing and may be overwritten by the user.
  39224. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39225. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39226. * @param update the boolean update value actually passed to setParticles()
  39227. */
  39228. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  39229. };
  39230. /**
  39231. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  39232. * This will be passed three parameters.
  39233. * This does nothing and may be overwritten by the user.
  39234. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39235. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39236. * @param update the boolean update value actually passed to setParticles()
  39237. */
  39238. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  39239. };
  39240. return SolidParticleSystem;
  39241. }());
  39242. BABYLON.SolidParticleSystem = SolidParticleSystem;
  39243. })(BABYLON || (BABYLON = {}));
  39244. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  39245. /// <reference path="babylon.mesh.ts" />
  39246. var BABYLON;
  39247. (function (BABYLON) {
  39248. var GroundMesh = (function (_super) {
  39249. __extends(GroundMesh, _super);
  39250. function GroundMesh(name, scene) {
  39251. var _this = _super.call(this, name, scene) || this;
  39252. _this.generateOctree = false;
  39253. _this._worldInverse = new BABYLON.Matrix();
  39254. return _this;
  39255. }
  39256. GroundMesh.prototype.getClassName = function () {
  39257. return "GroundMesh";
  39258. };
  39259. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  39260. get: function () {
  39261. return Math.min(this._subdivisionsX, this._subdivisionsY);
  39262. },
  39263. enumerable: true,
  39264. configurable: true
  39265. });
  39266. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  39267. get: function () {
  39268. return this._subdivisionsX;
  39269. },
  39270. enumerable: true,
  39271. configurable: true
  39272. });
  39273. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  39274. get: function () {
  39275. return this._subdivisionsY;
  39276. },
  39277. enumerable: true,
  39278. configurable: true
  39279. });
  39280. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  39281. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  39282. this._subdivisionsX = chunksCount;
  39283. this._subdivisionsY = chunksCount;
  39284. this.subdivide(chunksCount);
  39285. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  39286. };
  39287. /**
  39288. * Returns a height (y) value in the Worl system :
  39289. * the ground altitude at the coordinates (x, z) expressed in the World system.
  39290. * Returns the ground y position if (x, z) are outside the ground surface.
  39291. */
  39292. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  39293. var world = this.getWorldMatrix();
  39294. var invMat = BABYLON.Tmp.Matrix[5];
  39295. world.invertToRef(invMat);
  39296. var tmpVect = BABYLON.Tmp.Vector3[8];
  39297. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  39298. x = tmpVect.x;
  39299. z = tmpVect.z;
  39300. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39301. return this.position.y;
  39302. }
  39303. if (!this._heightQuads || this._heightQuads.length == 0) {
  39304. this._initHeightQuads();
  39305. this._computeHeightQuads();
  39306. }
  39307. var facet = this._getFacetAt(x, z);
  39308. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  39309. // return y in the World system
  39310. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  39311. return tmpVect.y;
  39312. };
  39313. /**
  39314. * Returns a normalized vector (Vector3) orthogonal to the ground
  39315. * at the ground coordinates (x, z) expressed in the World system.
  39316. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  39317. */
  39318. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  39319. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  39320. this.getNormalAtCoordinatesToRef(x, z, normal);
  39321. return normal;
  39322. };
  39323. /**
  39324. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  39325. * at the ground coordinates (x, z) expressed in the World system.
  39326. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  39327. * Returns the GroundMesh.
  39328. */
  39329. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  39330. var world = this.getWorldMatrix();
  39331. var tmpMat = BABYLON.Tmp.Matrix[5];
  39332. world.invertToRef(tmpMat);
  39333. var tmpVect = BABYLON.Tmp.Vector3[8];
  39334. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  39335. x = tmpVect.x;
  39336. z = tmpVect.z;
  39337. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39338. return this;
  39339. }
  39340. if (!this._heightQuads || this._heightQuads.length == 0) {
  39341. this._initHeightQuads();
  39342. this._computeHeightQuads();
  39343. }
  39344. var facet = this._getFacetAt(x, z);
  39345. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  39346. return this;
  39347. };
  39348. /**
  39349. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  39350. * if the ground has been updated.
  39351. * This can be used in the render loop.
  39352. * Returns the GroundMesh.
  39353. */
  39354. GroundMesh.prototype.updateCoordinateHeights = function () {
  39355. if (!this._heightQuads || this._heightQuads.length == 0) {
  39356. this._initHeightQuads();
  39357. }
  39358. this._computeHeightQuads();
  39359. return this;
  39360. };
  39361. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  39362. GroundMesh.prototype._getFacetAt = function (x, z) {
  39363. // retrieve col and row from x, z coordinates in the ground local system
  39364. var subdivisionsX = this._subdivisionsX;
  39365. var subdivisionsY = this._subdivisionsY;
  39366. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  39367. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  39368. var quad = this._heightQuads[row * this._subdivisionsX + col];
  39369. var facet;
  39370. if (z < quad.slope.x * x + quad.slope.y) {
  39371. facet = quad.facet1;
  39372. }
  39373. else {
  39374. facet = quad.facet2;
  39375. }
  39376. return facet;
  39377. };
  39378. // Creates and populates the heightMap array with "facet" elements :
  39379. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  39380. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39381. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39382. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39383. // Returns the GroundMesh.
  39384. GroundMesh.prototype._initHeightQuads = function () {
  39385. var subdivisionsX = this._subdivisionsX;
  39386. var subdivisionsY = this._subdivisionsY;
  39387. this._heightQuads = new Array();
  39388. for (var row = 0; row < subdivisionsY; row++) {
  39389. for (var col = 0; col < subdivisionsX; col++) {
  39390. 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) };
  39391. this._heightQuads[row * subdivisionsX + col] = quad;
  39392. }
  39393. }
  39394. return this;
  39395. };
  39396. // Compute each quad element values and update the the heightMap array :
  39397. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39398. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39399. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39400. // Returns the GroundMesh.
  39401. GroundMesh.prototype._computeHeightQuads = function () {
  39402. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39403. var v1 = BABYLON.Tmp.Vector3[3];
  39404. var v2 = BABYLON.Tmp.Vector3[2];
  39405. var v3 = BABYLON.Tmp.Vector3[1];
  39406. var v4 = BABYLON.Tmp.Vector3[0];
  39407. var v1v2 = BABYLON.Tmp.Vector3[4];
  39408. var v1v3 = BABYLON.Tmp.Vector3[5];
  39409. var v1v4 = BABYLON.Tmp.Vector3[6];
  39410. var norm1 = BABYLON.Tmp.Vector3[7];
  39411. var norm2 = BABYLON.Tmp.Vector3[8];
  39412. var i = 0;
  39413. var j = 0;
  39414. var k = 0;
  39415. var cd = 0; // 2D slope coefficient : z = cd * x + h
  39416. var h = 0;
  39417. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  39418. var d2 = 0;
  39419. var subdivisionsX = this._subdivisionsX;
  39420. var subdivisionsY = this._subdivisionsY;
  39421. for (var row = 0; row < subdivisionsY; row++) {
  39422. for (var col = 0; col < subdivisionsX; col++) {
  39423. i = col * 3;
  39424. j = row * (subdivisionsX + 1) * 3;
  39425. k = (row + 1) * (subdivisionsX + 1) * 3;
  39426. v1.x = positions[j + i];
  39427. v1.y = positions[j + i + 1];
  39428. v1.z = positions[j + i + 2];
  39429. v2.x = positions[j + i + 3];
  39430. v2.y = positions[j + i + 4];
  39431. v2.z = positions[j + i + 5];
  39432. v3.x = positions[k + i];
  39433. v3.y = positions[k + i + 1];
  39434. v3.z = positions[k + i + 2];
  39435. v4.x = positions[k + i + 3];
  39436. v4.y = positions[k + i + 4];
  39437. v4.z = positions[k + i + 5];
  39438. // 2D slope V1V4
  39439. cd = (v4.z - v1.z) / (v4.x - v1.x);
  39440. h = v1.z - cd * v1.x; // v1 belongs to the slope
  39441. // facet equations :
  39442. // we compute each facet normal vector
  39443. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  39444. // we compute the value d by applying the equation to v1 which belongs to the plane
  39445. // then we store the facet equation in a Vector4
  39446. v2.subtractToRef(v1, v1v2);
  39447. v3.subtractToRef(v1, v1v3);
  39448. v4.subtractToRef(v1, v1v4);
  39449. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  39450. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  39451. norm1.normalize();
  39452. norm2.normalize();
  39453. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  39454. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  39455. var quad = this._heightQuads[row * subdivisionsX + col];
  39456. quad.slope.copyFromFloats(cd, h);
  39457. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  39458. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  39459. }
  39460. }
  39461. return this;
  39462. };
  39463. GroundMesh.prototype.serialize = function (serializationObject) {
  39464. _super.prototype.serialize.call(this, serializationObject);
  39465. serializationObject.subdivisionsX = this._subdivisionsX;
  39466. serializationObject.subdivisionsY = this._subdivisionsY;
  39467. serializationObject.minX = this._minX;
  39468. serializationObject.maxX = this._maxX;
  39469. serializationObject.minZ = this._minZ;
  39470. serializationObject.maxZ = this._maxZ;
  39471. serializationObject.width = this._width;
  39472. serializationObject.height = this._height;
  39473. };
  39474. GroundMesh.Parse = function (parsedMesh, scene) {
  39475. var result = new GroundMesh(parsedMesh.name, scene);
  39476. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  39477. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  39478. result._minX = parsedMesh.minX;
  39479. result._maxX = parsedMesh.maxX;
  39480. result._minZ = parsedMesh.minZ;
  39481. result._maxZ = parsedMesh.maxZ;
  39482. result._width = parsedMesh.width;
  39483. result._height = parsedMesh.height;
  39484. return result;
  39485. };
  39486. return GroundMesh;
  39487. }(BABYLON.Mesh));
  39488. BABYLON.GroundMesh = GroundMesh;
  39489. })(BABYLON || (BABYLON = {}));
  39490. //# sourceMappingURL=babylon.groundMesh.js.map
  39491. var BABYLON;
  39492. (function (BABYLON) {
  39493. /**
  39494. * Creates an instance based on a source mesh.
  39495. */
  39496. var InstancedMesh = (function (_super) {
  39497. __extends(InstancedMesh, _super);
  39498. function InstancedMesh(name, source) {
  39499. var _this = _super.call(this, name, source.getScene()) || this;
  39500. source.instances.push(_this);
  39501. _this._sourceMesh = source;
  39502. _this.position.copyFrom(source.position);
  39503. _this.rotation.copyFrom(source.rotation);
  39504. _this.scaling.copyFrom(source.scaling);
  39505. if (source.rotationQuaternion) {
  39506. _this.rotationQuaternion = source.rotationQuaternion.clone();
  39507. }
  39508. _this.infiniteDistance = source.infiniteDistance;
  39509. _this.setPivotMatrix(source.getPivotMatrix());
  39510. _this.refreshBoundingInfo();
  39511. _this._syncSubMeshes();
  39512. return _this;
  39513. }
  39514. /**
  39515. * Returns the string "InstancedMesh".
  39516. */
  39517. InstancedMesh.prototype.getClassName = function () {
  39518. return "InstancedMesh";
  39519. };
  39520. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  39521. // Methods
  39522. get: function () {
  39523. return this._sourceMesh.receiveShadows;
  39524. },
  39525. enumerable: true,
  39526. configurable: true
  39527. });
  39528. Object.defineProperty(InstancedMesh.prototype, "material", {
  39529. get: function () {
  39530. return this._sourceMesh.material;
  39531. },
  39532. enumerable: true,
  39533. configurable: true
  39534. });
  39535. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  39536. get: function () {
  39537. return this._sourceMesh.visibility;
  39538. },
  39539. enumerable: true,
  39540. configurable: true
  39541. });
  39542. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  39543. get: function () {
  39544. return this._sourceMesh.skeleton;
  39545. },
  39546. enumerable: true,
  39547. configurable: true
  39548. });
  39549. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  39550. get: function () {
  39551. return this._sourceMesh.renderingGroupId;
  39552. },
  39553. enumerable: true,
  39554. configurable: true
  39555. });
  39556. /**
  39557. * Returns the total number of vertices (integer).
  39558. */
  39559. InstancedMesh.prototype.getTotalVertices = function () {
  39560. return this._sourceMesh.getTotalVertices();
  39561. };
  39562. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  39563. get: function () {
  39564. return this._sourceMesh;
  39565. },
  39566. enumerable: true,
  39567. configurable: true
  39568. });
  39569. /**
  39570. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  39571. */
  39572. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  39573. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  39574. };
  39575. /**
  39576. * Sets the vertex data of the mesh geometry for the requested `kind`.
  39577. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  39578. * The `data` are either a numeric array either a Float32Array.
  39579. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  39580. * 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).
  39581. * Note that a new underlying VertexBuffer object is created each call.
  39582. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  39583. *
  39584. * Possible `kind` values :
  39585. * - BABYLON.VertexBuffer.PositionKind
  39586. * - BABYLON.VertexBuffer.UVKind
  39587. * - BABYLON.VertexBuffer.UV2Kind
  39588. * - BABYLON.VertexBuffer.UV3Kind
  39589. * - BABYLON.VertexBuffer.UV4Kind
  39590. * - BABYLON.VertexBuffer.UV5Kind
  39591. * - BABYLON.VertexBuffer.UV6Kind
  39592. * - BABYLON.VertexBuffer.ColorKind
  39593. * - BABYLON.VertexBuffer.MatricesIndicesKind
  39594. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  39595. * - BABYLON.VertexBuffer.MatricesWeightsKind
  39596. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  39597. *
  39598. * Returns the Mesh.
  39599. */
  39600. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39601. if (this.sourceMesh) {
  39602. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  39603. }
  39604. return this.sourceMesh;
  39605. };
  39606. /**
  39607. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  39608. * If the mesh has no geometry, it is simply returned as it is.
  39609. * The `data` are either a numeric array either a Float32Array.
  39610. * No new underlying VertexBuffer object is created.
  39611. * 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.
  39612. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  39613. *
  39614. * Possible `kind` values :
  39615. * - BABYLON.VertexBuffer.PositionKind
  39616. * - BABYLON.VertexBuffer.UVKind
  39617. * - BABYLON.VertexBuffer.UV2Kind
  39618. * - BABYLON.VertexBuffer.UV3Kind
  39619. * - BABYLON.VertexBuffer.UV4Kind
  39620. * - BABYLON.VertexBuffer.UV5Kind
  39621. * - BABYLON.VertexBuffer.UV6Kind
  39622. * - BABYLON.VertexBuffer.ColorKind
  39623. * - BABYLON.VertexBuffer.MatricesIndicesKind
  39624. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  39625. * - BABYLON.VertexBuffer.MatricesWeightsKind
  39626. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  39627. *
  39628. * Returns the Mesh.
  39629. */
  39630. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  39631. if (this.sourceMesh) {
  39632. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  39633. }
  39634. return this.sourceMesh;
  39635. };
  39636. /**
  39637. * Sets the mesh indices.
  39638. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  39639. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  39640. * This method creates a new index buffer each call.
  39641. * Returns the Mesh.
  39642. */
  39643. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  39644. if (this.sourceMesh) {
  39645. this.sourceMesh.setIndices(indices, totalVertices);
  39646. }
  39647. return this.sourceMesh;
  39648. };
  39649. /**
  39650. * Boolean : True if the mesh owns the requested kind of data.
  39651. */
  39652. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  39653. return this._sourceMesh.isVerticesDataPresent(kind);
  39654. };
  39655. /**
  39656. * Returns an array of indices (IndicesArray).
  39657. */
  39658. InstancedMesh.prototype.getIndices = function () {
  39659. return this._sourceMesh.getIndices();
  39660. };
  39661. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  39662. get: function () {
  39663. return this._sourceMesh._positions;
  39664. },
  39665. enumerable: true,
  39666. configurable: true
  39667. });
  39668. /**
  39669. * Sets a new updated BoundingInfo to the mesh.
  39670. * Returns the mesh.
  39671. */
  39672. InstancedMesh.prototype.refreshBoundingInfo = function () {
  39673. var meshBB = this._sourceMesh.getBoundingInfo();
  39674. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  39675. this._updateBoundingInfo();
  39676. return this;
  39677. };
  39678. InstancedMesh.prototype._preActivate = function () {
  39679. if (this._currentLOD) {
  39680. this._currentLOD._preActivate();
  39681. }
  39682. return this;
  39683. };
  39684. InstancedMesh.prototype._activate = function (renderId) {
  39685. if (this._currentLOD) {
  39686. this._currentLOD._registerInstanceForRenderId(this, renderId);
  39687. }
  39688. return this;
  39689. };
  39690. /**
  39691. * Returns the current associated LOD AbstractMesh.
  39692. */
  39693. InstancedMesh.prototype.getLOD = function (camera) {
  39694. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  39695. if (this._currentLOD === this.sourceMesh) {
  39696. return this;
  39697. }
  39698. return this._currentLOD;
  39699. };
  39700. InstancedMesh.prototype._syncSubMeshes = function () {
  39701. this.releaseSubMeshes();
  39702. if (this._sourceMesh.subMeshes) {
  39703. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  39704. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  39705. }
  39706. }
  39707. return this;
  39708. };
  39709. InstancedMesh.prototype._generatePointsArray = function () {
  39710. return this._sourceMesh._generatePointsArray();
  39711. };
  39712. /**
  39713. * Creates a new InstancedMesh from the current mesh.
  39714. * - name (string) : the cloned mesh name
  39715. * - newParent (optional Node) : the optional Node to parent the clone to.
  39716. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  39717. *
  39718. * Returns the clone.
  39719. */
  39720. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  39721. var result = this._sourceMesh.createInstance(name);
  39722. // Deep copy
  39723. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  39724. // Bounding info
  39725. this.refreshBoundingInfo();
  39726. // Parent
  39727. if (newParent) {
  39728. result.parent = newParent;
  39729. }
  39730. if (!doNotCloneChildren) {
  39731. // Children
  39732. for (var index = 0; index < this.getScene().meshes.length; index++) {
  39733. var mesh = this.getScene().meshes[index];
  39734. if (mesh.parent === this) {
  39735. mesh.clone(mesh.name, result);
  39736. }
  39737. }
  39738. }
  39739. result.computeWorldMatrix(true);
  39740. return result;
  39741. };
  39742. /**
  39743. * Disposes the InstancedMesh.
  39744. * Returns nothing.
  39745. */
  39746. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  39747. // Remove from mesh
  39748. var index = this._sourceMesh.instances.indexOf(this);
  39749. this._sourceMesh.instances.splice(index, 1);
  39750. _super.prototype.dispose.call(this, doNotRecurse);
  39751. };
  39752. return InstancedMesh;
  39753. }(BABYLON.AbstractMesh));
  39754. BABYLON.InstancedMesh = InstancedMesh;
  39755. })(BABYLON || (BABYLON = {}));
  39756. //# sourceMappingURL=babylon.instancedMesh.js.map
  39757. /// <reference path="babylon.mesh.ts" />
  39758. var BABYLON;
  39759. (function (BABYLON) {
  39760. var LinesMesh = (function (_super) {
  39761. __extends(LinesMesh, _super);
  39762. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  39763. if (parent === void 0) { parent = null; }
  39764. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  39765. _this.useVertexColor = useVertexColor;
  39766. _this.color = new BABYLON.Color3(1, 1, 1);
  39767. _this.alpha = 1;
  39768. if (source) {
  39769. _this.color = source.color.clone();
  39770. _this.alpha = source.alpha;
  39771. _this.useVertexColor = source.useVertexColor;
  39772. }
  39773. _this._intersectionThreshold = 0.1;
  39774. var options = {
  39775. attributes: [BABYLON.VertexBuffer.PositionKind],
  39776. uniforms: ["world", "viewProjection"],
  39777. needAlphaBlending: false,
  39778. };
  39779. if (!useVertexColor) {
  39780. options.uniforms.push("color");
  39781. options.needAlphaBlending = true;
  39782. }
  39783. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  39784. return _this;
  39785. }
  39786. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  39787. /**
  39788. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  39789. * This margin is expressed in world space coordinates, so its value may vary.
  39790. * Default value is 0.1
  39791. * @returns the intersection Threshold value.
  39792. */
  39793. get: function () {
  39794. return this._intersectionThreshold;
  39795. },
  39796. /**
  39797. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  39798. * This margin is expressed in world space coordinates, so its value may vary.
  39799. * @param value the new threshold to apply
  39800. */
  39801. set: function (value) {
  39802. if (this._intersectionThreshold === value) {
  39803. return;
  39804. }
  39805. this._intersectionThreshold = value;
  39806. if (this.geometry) {
  39807. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  39808. }
  39809. },
  39810. enumerable: true,
  39811. configurable: true
  39812. });
  39813. /**
  39814. * Returns the string "LineMesh"
  39815. */
  39816. LinesMesh.prototype.getClassName = function () {
  39817. return "LinesMesh";
  39818. };
  39819. Object.defineProperty(LinesMesh.prototype, "material", {
  39820. get: function () {
  39821. return this._colorShader;
  39822. },
  39823. enumerable: true,
  39824. configurable: true
  39825. });
  39826. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  39827. get: function () {
  39828. return false;
  39829. },
  39830. enumerable: true,
  39831. configurable: true
  39832. });
  39833. LinesMesh.prototype.createInstance = function (name) {
  39834. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  39835. return null;
  39836. };
  39837. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  39838. // VBOs
  39839. this._geometry._bind(this._colorShader.getEffect());
  39840. // Color
  39841. if (!this.useVertexColor) {
  39842. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  39843. }
  39844. return this;
  39845. };
  39846. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  39847. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  39848. return this;
  39849. }
  39850. var engine = this.getScene().getEngine();
  39851. // Draw order
  39852. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  39853. return this;
  39854. };
  39855. LinesMesh.prototype.dispose = function (doNotRecurse) {
  39856. this._colorShader.dispose();
  39857. _super.prototype.dispose.call(this, doNotRecurse);
  39858. };
  39859. /**
  39860. * Returns a new LineMesh object cloned from the current one.
  39861. */
  39862. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  39863. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  39864. };
  39865. return LinesMesh;
  39866. }(BABYLON.Mesh));
  39867. BABYLON.LinesMesh = LinesMesh;
  39868. })(BABYLON || (BABYLON = {}));
  39869. //# sourceMappingURL=babylon.linesMesh.js.map
  39870. var BABYLON;
  39871. (function (BABYLON) {
  39872. var ShaderMaterial = (function (_super) {
  39873. __extends(ShaderMaterial, _super);
  39874. function ShaderMaterial(name, scene, shaderPath, options) {
  39875. var _this = _super.call(this, name, scene) || this;
  39876. _this._textures = {};
  39877. _this._textureArrays = {};
  39878. _this._floats = {};
  39879. _this._floatsArrays = {};
  39880. _this._colors3 = {};
  39881. _this._colors4 = {};
  39882. _this._vectors2 = {};
  39883. _this._vectors3 = {};
  39884. _this._vectors4 = {};
  39885. _this._matrices = {};
  39886. _this._matrices3x3 = {};
  39887. _this._matrices2x2 = {};
  39888. _this._vectors3Arrays = {};
  39889. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39890. _this._shaderPath = shaderPath;
  39891. options.needAlphaBlending = options.needAlphaBlending || false;
  39892. options.needAlphaTesting = options.needAlphaTesting || false;
  39893. options.attributes = options.attributes || ["position", "normal", "uv"];
  39894. options.uniforms = options.uniforms || ["worldViewProjection"];
  39895. options.uniformBuffers = options.uniformBuffers || [];
  39896. options.samplers = options.samplers || [];
  39897. options.defines = options.defines || [];
  39898. _this._options = options;
  39899. return _this;
  39900. }
  39901. ShaderMaterial.prototype.getClassName = function () {
  39902. return "ShaderMaterial";
  39903. };
  39904. ShaderMaterial.prototype.needAlphaBlending = function () {
  39905. return this._options.needAlphaBlending;
  39906. };
  39907. ShaderMaterial.prototype.needAlphaTesting = function () {
  39908. return this._options.needAlphaTesting;
  39909. };
  39910. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39911. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39912. this._options.uniforms.push(uniformName);
  39913. }
  39914. };
  39915. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39916. if (this._options.samplers.indexOf(name) === -1) {
  39917. this._options.samplers.push(name);
  39918. }
  39919. this._textures[name] = texture;
  39920. return this;
  39921. };
  39922. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  39923. if (this._options.samplers.indexOf(name) === -1) {
  39924. this._options.samplers.push(name);
  39925. }
  39926. this._checkUniform(name);
  39927. this._textureArrays[name] = textures;
  39928. return this;
  39929. };
  39930. ShaderMaterial.prototype.setFloat = function (name, value) {
  39931. this._checkUniform(name);
  39932. this._floats[name] = value;
  39933. return this;
  39934. };
  39935. ShaderMaterial.prototype.setFloats = function (name, value) {
  39936. this._checkUniform(name);
  39937. this._floatsArrays[name] = value;
  39938. return this;
  39939. };
  39940. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39941. this._checkUniform(name);
  39942. this._colors3[name] = value;
  39943. return this;
  39944. };
  39945. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39946. this._checkUniform(name);
  39947. this._colors4[name] = value;
  39948. return this;
  39949. };
  39950. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39951. this._checkUniform(name);
  39952. this._vectors2[name] = value;
  39953. return this;
  39954. };
  39955. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39956. this._checkUniform(name);
  39957. this._vectors3[name] = value;
  39958. return this;
  39959. };
  39960. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39961. this._checkUniform(name);
  39962. this._vectors4[name] = value;
  39963. return this;
  39964. };
  39965. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39966. this._checkUniform(name);
  39967. this._matrices[name] = value;
  39968. return this;
  39969. };
  39970. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39971. this._checkUniform(name);
  39972. this._matrices3x3[name] = value;
  39973. return this;
  39974. };
  39975. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39976. this._checkUniform(name);
  39977. this._matrices2x2[name] = value;
  39978. return this;
  39979. };
  39980. ShaderMaterial.prototype.setArray3 = function (name, value) {
  39981. this._checkUniform(name);
  39982. this._vectors3Arrays[name] = value;
  39983. return this;
  39984. };
  39985. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  39986. if (!mesh) {
  39987. return true;
  39988. }
  39989. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  39990. return false;
  39991. }
  39992. return false;
  39993. };
  39994. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39995. var scene = this.getScene();
  39996. var engine = scene.getEngine();
  39997. if (!this.checkReadyOnEveryCall) {
  39998. if (this._renderId === scene.getRenderId()) {
  39999. if (this._checkCache(scene, mesh, useInstances)) {
  40000. return true;
  40001. }
  40002. }
  40003. }
  40004. // Instances
  40005. var defines = [];
  40006. var attribs = [];
  40007. var fallbacks = new BABYLON.EffectFallbacks();
  40008. if (useInstances) {
  40009. defines.push("#define INSTANCES");
  40010. }
  40011. for (var index = 0; index < this._options.defines.length; index++) {
  40012. defines.push(this._options.defines[index]);
  40013. }
  40014. for (var index = 0; index < this._options.attributes.length; index++) {
  40015. attribs.push(this._options.attributes[index]);
  40016. }
  40017. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40018. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40019. defines.push("#define VERTEXCOLOR");
  40020. }
  40021. // Bones
  40022. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40023. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40024. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40025. if (mesh.numBoneInfluencers > 4) {
  40026. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40027. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40028. }
  40029. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40030. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40031. fallbacks.addCPUSkinningFallback(0, mesh);
  40032. }
  40033. else {
  40034. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40035. }
  40036. // Textures
  40037. for (var name in this._textures) {
  40038. if (!this._textures[name].isReady()) {
  40039. return false;
  40040. }
  40041. }
  40042. // Alpha test
  40043. if (engine.getAlphaTesting()) {
  40044. defines.push("#define ALPHATEST");
  40045. }
  40046. var previousEffect = this._effect;
  40047. var join = defines.join("\n");
  40048. this._effect = engine.createEffect(this._shaderPath, {
  40049. attributes: attribs,
  40050. uniformsNames: this._options.uniforms,
  40051. uniformBuffersNames: this._options.uniformBuffers,
  40052. samplers: this._options.samplers,
  40053. defines: join,
  40054. fallbacks: fallbacks,
  40055. onCompiled: this.onCompiled,
  40056. onError: this.onError
  40057. }, engine);
  40058. if (!this._effect.isReady()) {
  40059. return false;
  40060. }
  40061. if (previousEffect !== this._effect) {
  40062. scene.resetCachedMaterial();
  40063. }
  40064. this._renderId = scene.getRenderId();
  40065. return true;
  40066. };
  40067. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40068. var scene = this.getScene();
  40069. if (this._options.uniforms.indexOf("world") !== -1) {
  40070. this._effect.setMatrix("world", world);
  40071. }
  40072. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40073. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40074. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40075. }
  40076. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40077. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40078. }
  40079. };
  40080. ShaderMaterial.prototype.bind = function (world, mesh) {
  40081. // Std values
  40082. this.bindOnlyWorldMatrix(world);
  40083. if (this.getScene().getCachedMaterial() !== this) {
  40084. if (this._options.uniforms.indexOf("view") !== -1) {
  40085. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40086. }
  40087. if (this._options.uniforms.indexOf("projection") !== -1) {
  40088. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40089. }
  40090. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40091. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40092. }
  40093. // Bones
  40094. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40095. var name;
  40096. // Texture
  40097. for (name in this._textures) {
  40098. this._effect.setTexture(name, this._textures[name]);
  40099. }
  40100. // Texture arrays
  40101. for (name in this._textureArrays) {
  40102. this._effect.setTextureArray(name, this._textureArrays[name]);
  40103. }
  40104. // Float
  40105. for (name in this._floats) {
  40106. this._effect.setFloat(name, this._floats[name]);
  40107. }
  40108. // Float s
  40109. for (name in this._floatsArrays) {
  40110. this._effect.setArray(name, this._floatsArrays[name]);
  40111. }
  40112. // Color3
  40113. for (name in this._colors3) {
  40114. this._effect.setColor3(name, this._colors3[name]);
  40115. }
  40116. // Color4
  40117. for (name in this._colors4) {
  40118. var color = this._colors4[name];
  40119. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40120. }
  40121. // Vector2
  40122. for (name in this._vectors2) {
  40123. this._effect.setVector2(name, this._vectors2[name]);
  40124. }
  40125. // Vector3
  40126. for (name in this._vectors3) {
  40127. this._effect.setVector3(name, this._vectors3[name]);
  40128. }
  40129. // Vector4
  40130. for (name in this._vectors4) {
  40131. this._effect.setVector4(name, this._vectors4[name]);
  40132. }
  40133. // Matrix
  40134. for (name in this._matrices) {
  40135. this._effect.setMatrix(name, this._matrices[name]);
  40136. }
  40137. // Matrix 3x3
  40138. for (name in this._matrices3x3) {
  40139. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40140. }
  40141. // Matrix 2x2
  40142. for (name in this._matrices2x2) {
  40143. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40144. }
  40145. // Vector3Array
  40146. for (name in this._vectors3Arrays) {
  40147. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40148. }
  40149. }
  40150. this._afterBind(mesh);
  40151. };
  40152. ShaderMaterial.prototype.clone = function (name) {
  40153. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40154. return newShaderMaterial;
  40155. };
  40156. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40157. if (forceDisposeTextures) {
  40158. var name;
  40159. for (name in this._textures) {
  40160. this._textures[name].dispose();
  40161. }
  40162. for (name in this._textureArrays) {
  40163. var array = this._textureArrays[name];
  40164. for (var index = 0; index < array.length; index++) {
  40165. array[index].dispose();
  40166. }
  40167. }
  40168. }
  40169. this._textures = {};
  40170. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40171. };
  40172. ShaderMaterial.prototype.serialize = function () {
  40173. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40174. serializationObject.customType = "BABYLON.ShaderMaterial";
  40175. serializationObject.options = this._options;
  40176. serializationObject.shaderPath = this._shaderPath;
  40177. var name;
  40178. // Texture
  40179. serializationObject.textures = {};
  40180. for (name in this._textures) {
  40181. serializationObject.textures[name] = this._textures[name].serialize();
  40182. }
  40183. // Texture arrays
  40184. serializationObject.textureArrays = {};
  40185. for (name in this._textureArrays) {
  40186. serializationObject.textureArrays[name] = [];
  40187. var array = this._textureArrays[name];
  40188. for (var index = 0; index < array.length; index++) {
  40189. serializationObject.textureArrays[name].push(array[index].serialize());
  40190. }
  40191. }
  40192. // Float
  40193. serializationObject.floats = {};
  40194. for (name in this._floats) {
  40195. serializationObject.floats[name] = this._floats[name];
  40196. }
  40197. // Float s
  40198. serializationObject.floatArrays = {};
  40199. for (name in this._floatsArrays) {
  40200. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40201. }
  40202. // Color3
  40203. serializationObject.colors3 = {};
  40204. for (name in this._colors3) {
  40205. serializationObject.colors3[name] = this._colors3[name].asArray();
  40206. }
  40207. // Color4
  40208. serializationObject.colors4 = {};
  40209. for (name in this._colors4) {
  40210. serializationObject.colors4[name] = this._colors4[name].asArray();
  40211. }
  40212. // Vector2
  40213. serializationObject.vectors2 = {};
  40214. for (name in this._vectors2) {
  40215. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40216. }
  40217. // Vector3
  40218. serializationObject.vectors3 = {};
  40219. for (name in this._vectors3) {
  40220. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40221. }
  40222. // Vector4
  40223. serializationObject.vectors4 = {};
  40224. for (name in this._vectors4) {
  40225. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40226. }
  40227. // Matrix
  40228. serializationObject.matrices = {};
  40229. for (name in this._matrices) {
  40230. serializationObject.matrices[name] = this._matrices[name].asArray();
  40231. }
  40232. // Matrix 3x3
  40233. serializationObject.matrices3x3 = {};
  40234. for (name in this._matrices3x3) {
  40235. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40236. }
  40237. // Matrix 2x2
  40238. serializationObject.matrices2x2 = {};
  40239. for (name in this._matrices2x2) {
  40240. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40241. }
  40242. // Vector3Array
  40243. serializationObject.vectors3Arrays = {};
  40244. for (name in this._vectors3Arrays) {
  40245. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40246. }
  40247. return serializationObject;
  40248. };
  40249. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40250. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40251. var name;
  40252. // Texture
  40253. for (name in source.textures) {
  40254. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40255. }
  40256. // Texture arrays
  40257. for (name in source.textureArrays) {
  40258. var array = source.textureArrays[name];
  40259. var textureArray = new Array();
  40260. for (var index = 0; index < array.length; index++) {
  40261. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40262. }
  40263. material.setTextureArray(name, textureArray);
  40264. }
  40265. // Float
  40266. for (name in source.floats) {
  40267. material.setFloat(name, source.floats[name]);
  40268. }
  40269. // Float s
  40270. for (name in source.floatsArrays) {
  40271. material.setFloats(name, source.floatsArrays[name]);
  40272. }
  40273. // Color3
  40274. for (name in source.colors3) {
  40275. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40276. }
  40277. // Color4
  40278. for (name in source.colors4) {
  40279. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40280. }
  40281. // Vector2
  40282. for (name in source.vectors2) {
  40283. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40284. }
  40285. // Vector3
  40286. for (name in source.vectors3) {
  40287. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40288. }
  40289. // Vector4
  40290. for (name in source.vectors4) {
  40291. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40292. }
  40293. // Matrix
  40294. for (name in source.matrices) {
  40295. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40296. }
  40297. // Matrix 3x3
  40298. for (name in source.matrices3x3) {
  40299. material.setMatrix3x3(name, source.matrices3x3[name]);
  40300. }
  40301. // Matrix 2x2
  40302. for (name in source.matrices2x2) {
  40303. material.setMatrix2x2(name, source.matrices2x2[name]);
  40304. }
  40305. // Vector3Array
  40306. for (name in source.vectors3Arrays) {
  40307. material.setArray3(name, source.vectors3Arrays[name]);
  40308. }
  40309. return material;
  40310. };
  40311. return ShaderMaterial;
  40312. }(BABYLON.Material));
  40313. BABYLON.ShaderMaterial = ShaderMaterial;
  40314. })(BABYLON || (BABYLON = {}));
  40315. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40316. var BABYLON;
  40317. (function (BABYLON) {
  40318. var MeshBuilder = (function () {
  40319. function MeshBuilder() {
  40320. }
  40321. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  40322. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  40323. return BABYLON.Mesh.DOUBLESIDE;
  40324. }
  40325. if (orientation === undefined || orientation === null) {
  40326. return BABYLON.Mesh.FRONTSIDE;
  40327. }
  40328. return orientation;
  40329. };
  40330. /**
  40331. * Creates a box mesh.
  40332. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  40333. * The parameter `size` sets the size (float) of each box side (default 1).
  40334. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  40335. * 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).
  40336. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40337. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40338. * 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).
  40339. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40341. */
  40342. MeshBuilder.CreateBox = function (name, options, scene) {
  40343. var box = new BABYLON.Mesh(name, scene);
  40344. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40345. box.sideOrientation = options.sideOrientation;
  40346. var vertexData = BABYLON.VertexData.CreateBox(options);
  40347. vertexData.applyToMesh(box, options.updatable);
  40348. return box;
  40349. };
  40350. /**
  40351. * Creates a sphere mesh.
  40352. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  40353. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  40354. * 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`).
  40355. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  40356. * 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
  40357. * 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).
  40358. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40359. * 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).
  40360. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40362. */
  40363. MeshBuilder.CreateSphere = function (name, options, scene) {
  40364. var sphere = new BABYLON.Mesh(name, scene);
  40365. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40366. sphere.sideOrientation = options.sideOrientation;
  40367. var vertexData = BABYLON.VertexData.CreateSphere(options);
  40368. vertexData.applyToMesh(sphere, options.updatable);
  40369. return sphere;
  40370. };
  40371. /**
  40372. * Creates a plane polygonal mesh. By default, this is a disc.
  40373. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  40374. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  40375. * 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.
  40376. * 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
  40377. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40378. * 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).
  40379. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40380. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40381. */
  40382. MeshBuilder.CreateDisc = function (name, options, scene) {
  40383. var disc = new BABYLON.Mesh(name, scene);
  40384. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40385. disc.sideOrientation = options.sideOrientation;
  40386. var vertexData = BABYLON.VertexData.CreateDisc(options);
  40387. vertexData.applyToMesh(disc, options.updatable);
  40388. return disc;
  40389. };
  40390. /**
  40391. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  40392. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  40393. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  40394. * 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`).
  40395. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  40396. * 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.
  40397. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40398. * 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).
  40399. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40401. */
  40402. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  40403. var sphere = new BABYLON.Mesh(name, scene);
  40404. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40405. sphere.sideOrientation = options.sideOrientation;
  40406. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  40407. vertexData.applyToMesh(sphere, options.updatable);
  40408. return sphere;
  40409. };
  40410. ;
  40411. /**
  40412. * Creates a ribbon mesh.
  40413. * 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.
  40414. *
  40415. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  40416. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  40417. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  40418. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  40419. * 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.
  40420. * 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.
  40421. * 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
  40422. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40423. * 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).
  40424. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40425. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40426. * 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.
  40427. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  40428. * 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
  40429. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  40430. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  40431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40432. */
  40433. MeshBuilder.CreateRibbon = function (name, options, scene) {
  40434. var pathArray = options.pathArray;
  40435. var closeArray = options.closeArray;
  40436. var closePath = options.closePath;
  40437. var offset = options.offset;
  40438. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40439. var instance = options.instance;
  40440. var updatable = options.updatable;
  40441. if (instance) {
  40442. // positionFunction : ribbon case
  40443. // only pathArray and sideOrientation parameters are taken into account for positions update
  40444. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  40445. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  40446. var positionFunction = function (positions) {
  40447. var minlg = pathArray[0].length;
  40448. var i = 0;
  40449. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  40450. for (var si = 1; si <= ns; si++) {
  40451. for (var p = 0; p < pathArray.length; p++) {
  40452. var path = pathArray[p];
  40453. var l = path.length;
  40454. minlg = (minlg < l) ? minlg : l;
  40455. var j = 0;
  40456. while (j < minlg) {
  40457. positions[i] = path[j].x;
  40458. positions[i + 1] = path[j].y;
  40459. positions[i + 2] = path[j].z;
  40460. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  40461. BABYLON.Tmp.Vector3[0].x = path[j].x;
  40462. }
  40463. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  40464. BABYLON.Tmp.Vector3[1].x = path[j].x;
  40465. }
  40466. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  40467. BABYLON.Tmp.Vector3[0].y = path[j].y;
  40468. }
  40469. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  40470. BABYLON.Tmp.Vector3[1].y = path[j].y;
  40471. }
  40472. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  40473. BABYLON.Tmp.Vector3[0].z = path[j].z;
  40474. }
  40475. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  40476. BABYLON.Tmp.Vector3[1].z = path[j].z;
  40477. }
  40478. j++;
  40479. i += 3;
  40480. }
  40481. if (instance._closePath) {
  40482. positions[i] = path[0].x;
  40483. positions[i + 1] = path[0].y;
  40484. positions[i + 2] = path[0].z;
  40485. i += 3;
  40486. }
  40487. }
  40488. }
  40489. };
  40490. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40491. positionFunction(positions);
  40492. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  40493. instance._boundingInfo.update(instance._worldMatrix);
  40494. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  40495. if (options.colors) {
  40496. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40497. for (var c = 0; c < options.colors.length; c++) {
  40498. colors[c * 4] = options.colors[c].r;
  40499. colors[c * 4 + 1] = options.colors[c].g;
  40500. colors[c * 4 + 2] = options.colors[c].b;
  40501. colors[c * 4 + 3] = options.colors[c].a;
  40502. }
  40503. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  40504. }
  40505. if (options.uvs) {
  40506. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40507. for (var i = 0; i < options.uvs.length; i++) {
  40508. uvs[i * 2] = options.uvs[i].x;
  40509. uvs[i * 2 + 1] = options.uvs[i].y;
  40510. }
  40511. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  40512. }
  40513. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  40514. var indices = instance.getIndices();
  40515. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40516. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  40517. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  40518. if (instance._closePath) {
  40519. var indexFirst = 0;
  40520. var indexLast = 0;
  40521. for (var p = 0; p < pathArray.length; p++) {
  40522. indexFirst = instance._idx[p] * 3;
  40523. if (p + 1 < pathArray.length) {
  40524. indexLast = (instance._idx[p + 1] - 1) * 3;
  40525. }
  40526. else {
  40527. indexLast = normals.length - 3;
  40528. }
  40529. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  40530. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  40531. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  40532. normals[indexLast] = normals[indexFirst];
  40533. normals[indexLast + 1] = normals[indexFirst + 1];
  40534. normals[indexLast + 2] = normals[indexFirst + 2];
  40535. }
  40536. }
  40537. if (!(instance.areNormalsFrozen)) {
  40538. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  40539. }
  40540. }
  40541. return instance;
  40542. }
  40543. else {
  40544. var ribbon = new BABYLON.Mesh(name, scene);
  40545. ribbon.sideOrientation = sideOrientation;
  40546. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  40547. if (closePath) {
  40548. ribbon._idx = vertexData._idx;
  40549. }
  40550. ribbon._closePath = closePath;
  40551. ribbon._closeArray = closeArray;
  40552. vertexData.applyToMesh(ribbon, updatable);
  40553. return ribbon;
  40554. }
  40555. };
  40556. /**
  40557. * Creates a cylinder or a cone mesh.
  40558. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  40559. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  40560. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  40561. * 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.
  40562. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  40563. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  40564. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  40565. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  40566. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  40567. * 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).
  40568. * 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
  40569. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  40570. * 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
  40571. * 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.
  40572. * If `enclose` is false, a ring surface is one element.
  40573. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  40574. * 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
  40575. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40576. * 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).
  40577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40579. */
  40580. MeshBuilder.CreateCylinder = function (name, options, scene) {
  40581. var cylinder = new BABYLON.Mesh(name, scene);
  40582. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40583. cylinder.sideOrientation = options.sideOrientation;
  40584. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  40585. vertexData.applyToMesh(cylinder, options.updatable);
  40586. return cylinder;
  40587. };
  40588. /**
  40589. * Creates a torus mesh.
  40590. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  40591. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  40592. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  40593. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  40594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40595. * 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).
  40596. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40598. */
  40599. MeshBuilder.CreateTorus = function (name, options, scene) {
  40600. var torus = new BABYLON.Mesh(name, scene);
  40601. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40602. torus.sideOrientation = options.sideOrientation;
  40603. var vertexData = BABYLON.VertexData.CreateTorus(options);
  40604. vertexData.applyToMesh(torus, options.updatable);
  40605. return torus;
  40606. };
  40607. /**
  40608. * Creates a torus knot mesh.
  40609. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  40610. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  40611. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  40612. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  40613. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  40614. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40615. * 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).
  40616. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40618. */
  40619. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  40620. var torusKnot = new BABYLON.Mesh(name, scene);
  40621. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40622. torusKnot.sideOrientation = options.sideOrientation;
  40623. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  40624. vertexData.applyToMesh(torusKnot, options.updatable);
  40625. return torusKnot;
  40626. };
  40627. /**
  40628. * Creates a line system mesh.
  40629. * A line system is a pool of many lines gathered in a single mesh.
  40630. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  40631. * 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.
  40632. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  40633. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  40634. * 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
  40635. * 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
  40636. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  40637. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40638. */
  40639. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  40640. var instance = options.instance;
  40641. var lines = options.lines;
  40642. if (instance) {
  40643. var positionFunction = function (positions) {
  40644. var i = 0;
  40645. for (var l = 0; l < lines.length; l++) {
  40646. var points = lines[l];
  40647. for (var p = 0; p < points.length; p++) {
  40648. positions[i] = points[p].x;
  40649. positions[i + 1] = points[p].y;
  40650. positions[i + 2] = points[p].z;
  40651. i += 3;
  40652. }
  40653. }
  40654. };
  40655. instance.updateMeshPositions(positionFunction, false);
  40656. return instance;
  40657. }
  40658. // line system creation
  40659. var lineSystem = new BABYLON.LinesMesh(name, scene);
  40660. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  40661. vertexData.applyToMesh(lineSystem, options.updatable);
  40662. return lineSystem;
  40663. };
  40664. /**
  40665. * Creates a line mesh.
  40666. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  40667. * 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.
  40668. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40669. * The parameter `points` is an array successive Vector3.
  40670. * 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
  40671. * When updating an instance, remember that only point positions can change, not the number of points.
  40672. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40673. */
  40674. MeshBuilder.CreateLines = function (name, options, scene) {
  40675. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  40676. return lines;
  40677. };
  40678. /**
  40679. * Creates a dashed line mesh.
  40680. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  40681. * 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.
  40682. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40683. * The parameter `points` is an array successive Vector3.
  40684. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  40685. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  40686. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  40687. * 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
  40688. * When updating an instance, remember that only point positions can change, not the number of points.
  40689. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40690. */
  40691. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  40692. var points = options.points;
  40693. var instance = options.instance;
  40694. var gapSize = options.gapSize;
  40695. var dashNb = options.dashNb;
  40696. var dashSize = options.dashSize;
  40697. if (instance) {
  40698. var positionFunction = function (positions) {
  40699. var curvect = BABYLON.Vector3.Zero();
  40700. var nbSeg = positions.length / 6;
  40701. var lg = 0;
  40702. var nb = 0;
  40703. var shft = 0;
  40704. var dashshft = 0;
  40705. var curshft = 0;
  40706. var p = 0;
  40707. var i = 0;
  40708. var j = 0;
  40709. for (i = 0; i < points.length - 1; i++) {
  40710. points[i + 1].subtractToRef(points[i], curvect);
  40711. lg += curvect.length();
  40712. }
  40713. shft = lg / nbSeg;
  40714. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  40715. for (i = 0; i < points.length - 1; i++) {
  40716. points[i + 1].subtractToRef(points[i], curvect);
  40717. nb = Math.floor(curvect.length() / shft);
  40718. curvect.normalize();
  40719. j = 0;
  40720. while (j < nb && p < positions.length) {
  40721. curshft = shft * j;
  40722. positions[p] = points[i].x + curshft * curvect.x;
  40723. positions[p + 1] = points[i].y + curshft * curvect.y;
  40724. positions[p + 2] = points[i].z + curshft * curvect.z;
  40725. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  40726. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  40727. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  40728. p += 6;
  40729. j++;
  40730. }
  40731. }
  40732. while (p < positions.length) {
  40733. positions[p] = points[i].x;
  40734. positions[p + 1] = points[i].y;
  40735. positions[p + 2] = points[i].z;
  40736. p += 3;
  40737. }
  40738. };
  40739. instance.updateMeshPositions(positionFunction, false);
  40740. return instance;
  40741. }
  40742. // dashed lines creation
  40743. var dashedLines = new BABYLON.LinesMesh(name, scene);
  40744. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  40745. vertexData.applyToMesh(dashedLines, options.updatable);
  40746. dashedLines.dashSize = dashSize;
  40747. dashedLines.gapSize = gapSize;
  40748. return dashedLines;
  40749. };
  40750. /**
  40751. * Creates an extruded shape mesh.
  40752. * 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.
  40753. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  40754. *
  40755. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40756. * 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
  40757. * extruded along the Z axis.
  40758. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40759. * 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.
  40760. * The parameter `scale` (float, default 1) is the value to scale the shape.
  40761. * 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
  40762. * 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
  40763. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40764. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40765. * 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).
  40766. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40767. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40768. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40769. */
  40770. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  40771. var path = options.path;
  40772. var shape = options.shape;
  40773. var scale = options.scale || 1;
  40774. var rotation = options.rotation || 0;
  40775. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40776. var updatable = options.updatable;
  40777. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40778. var instance = options.instance;
  40779. var invertUV = options.invertUV || false;
  40780. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40781. };
  40782. /**
  40783. * Creates an custom extruded shape mesh.
  40784. * 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.
  40785. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  40786. *
  40787. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40788. * 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
  40789. * extruded along the Z axis.
  40790. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40791. * 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
  40792. * and the distance of this point from the begining of the path :
  40793. * ```javascript
  40794. * var rotationFunction = function(i, distance) {
  40795. * // do things
  40796. * return rotationValue; }
  40797. * ```
  40798. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  40799. * 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
  40800. * and the distance of this point from the begining of the path :
  40801. * ```javascript
  40802. * var scaleFunction = function(i, distance) {
  40803. * // do things
  40804. * return scaleValue;}
  40805. * ```
  40806. * It must returns a float value that will be the scale value applied to the shape on each path point.
  40807. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  40808. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  40809. * 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
  40810. * 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
  40811. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40812. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40813. * 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).
  40814. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40815. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40816. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40817. */
  40818. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  40819. var path = options.path;
  40820. var shape = options.shape;
  40821. var scaleFunction = options.scaleFunction || (function () { return 1; });
  40822. var rotationFunction = options.rotationFunction || (function () { return 0; });
  40823. var ribbonCloseArray = options.ribbonCloseArray || false;
  40824. var ribbonClosePath = options.ribbonClosePath || false;
  40825. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40826. var updatable = options.updatable;
  40827. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40828. var instance = options.instance;
  40829. var invertUV = options.invertUV || false;
  40830. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40831. };
  40832. /**
  40833. * Creates lathe mesh.
  40834. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  40835. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  40836. *
  40837. * 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
  40838. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  40839. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  40840. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  40841. * 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.
  40842. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  40843. * 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
  40844. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40845. * 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).
  40846. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40847. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40848. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40849. */
  40850. MeshBuilder.CreateLathe = function (name, options, scene) {
  40851. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  40852. var closed = (options.closed === undefined) ? true : options.closed;
  40853. var shape = options.shape;
  40854. var radius = options.radius || 1;
  40855. var tessellation = options.tessellation || 64;
  40856. var updatable = options.updatable;
  40857. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40858. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40859. var pi2 = Math.PI * 2;
  40860. var paths = new Array();
  40861. var invertUV = options.invertUV || false;
  40862. var i = 0;
  40863. var p = 0;
  40864. var step = pi2 / tessellation * arc;
  40865. var rotated;
  40866. var path = new Array();
  40867. ;
  40868. for (i = 0; i <= tessellation; i++) {
  40869. var path = [];
  40870. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  40871. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  40872. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  40873. }
  40874. for (p = 0; p < shape.length; p++) {
  40875. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  40876. path.push(rotated);
  40877. }
  40878. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  40879. 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));
  40880. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  40881. }
  40882. paths.push(path);
  40883. }
  40884. // lathe ribbon
  40885. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40886. return lathe;
  40887. };
  40888. /**
  40889. * Creates a plane mesh.
  40890. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40891. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  40892. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  40893. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  40894. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40895. * 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).
  40896. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40897. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40898. */
  40899. MeshBuilder.CreatePlane = function (name, options, scene) {
  40900. var plane = new BABYLON.Mesh(name, scene);
  40901. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40902. plane.sideOrientation = options.sideOrientation;
  40903. var vertexData = BABYLON.VertexData.CreatePlane(options);
  40904. vertexData.applyToMesh(plane, options.updatable);
  40905. if (options.sourcePlane) {
  40906. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  40907. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  40908. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  40909. plane.rotate(vectorProduct, product);
  40910. }
  40911. return plane;
  40912. };
  40913. /**
  40914. * Creates a ground mesh.
  40915. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40916. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  40917. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  40918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40919. */
  40920. MeshBuilder.CreateGround = function (name, options, scene) {
  40921. var ground = new BABYLON.GroundMesh(name, scene);
  40922. ground._setReady(false);
  40923. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  40924. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  40925. ground._width = options.width || 1;
  40926. ground._height = options.height || 1;
  40927. ground._maxX = ground._width / 2;
  40928. ground._maxZ = ground._height / 2;
  40929. ground._minX = -ground._maxX;
  40930. ground._minZ = -ground._maxZ;
  40931. var vertexData = BABYLON.VertexData.CreateGround(options);
  40932. vertexData.applyToMesh(ground, options.updatable);
  40933. ground._setReady(true);
  40934. return ground;
  40935. };
  40936. /**
  40937. * Creates a tiled ground mesh.
  40938. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  40939. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  40940. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  40941. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  40942. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  40943. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  40944. * numbers of subdivisions on the ground width and height of each tile.
  40945. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40946. */
  40947. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  40948. var tiledGround = new BABYLON.Mesh(name, scene);
  40949. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  40950. vertexData.applyToMesh(tiledGround, options.updatable);
  40951. return tiledGround;
  40952. };
  40953. /**
  40954. * Creates a ground mesh from a height map.
  40955. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  40956. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  40957. * The parameter `url` sets the URL of the height map image resource.
  40958. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  40959. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  40960. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  40961. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  40962. * 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.
  40963. * 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).
  40964. * This function is passed the newly built mesh :
  40965. * ```javascript
  40966. * function(mesh) { // do things
  40967. * return; }
  40968. * ```
  40969. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40970. */
  40971. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  40972. var width = options.width || 10.0;
  40973. var height = options.height || 10.0;
  40974. var subdivisions = options.subdivisions || 1 | 0;
  40975. var minHeight = options.minHeight || 0.0;
  40976. var maxHeight = options.maxHeight || 10.0;
  40977. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  40978. var updatable = options.updatable;
  40979. var onReady = options.onReady;
  40980. var ground = new BABYLON.GroundMesh(name, scene);
  40981. ground._subdivisionsX = subdivisions;
  40982. ground._subdivisionsY = subdivisions;
  40983. ground._width = width;
  40984. ground._height = height;
  40985. ground._maxX = ground._width / 2.0;
  40986. ground._maxZ = ground._height / 2.0;
  40987. ground._minX = -ground._maxX;
  40988. ground._minZ = -ground._maxZ;
  40989. ground._setReady(false);
  40990. var onload = function (img) {
  40991. // Getting height map data
  40992. var canvas = document.createElement("canvas");
  40993. var context = canvas.getContext("2d");
  40994. var bufferWidth = img.width;
  40995. var bufferHeight = img.height;
  40996. canvas.width = bufferWidth;
  40997. canvas.height = bufferHeight;
  40998. context.drawImage(img, 0, 0);
  40999. // Create VertexData from map data
  41000. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  41001. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  41002. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  41003. width: width, height: height,
  41004. subdivisions: subdivisions,
  41005. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  41006. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  41007. });
  41008. vertexData.applyToMesh(ground, updatable);
  41009. ground._setReady(true);
  41010. //execute ready callback, if set
  41011. if (onReady) {
  41012. onReady(ground);
  41013. }
  41014. };
  41015. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  41016. return ground;
  41017. };
  41018. /**
  41019. * Creates a polygon mesh.
  41020. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  41021. * 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.
  41022. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41023. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41024. * 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).
  41025. * Remember you can only change the shape positions, not their number when updating a polygon.
  41026. */
  41027. MeshBuilder.CreatePolygon = function (name, options, scene) {
  41028. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41029. var shape = options.shape;
  41030. var holes = options.holes || [];
  41031. var depth = options.depth || 0;
  41032. var contours = [];
  41033. var hole = [];
  41034. for (var i = 0; i < shape.length; i++) {
  41035. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  41036. }
  41037. var epsilon = 0.00000001;
  41038. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  41039. contours.pop();
  41040. }
  41041. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  41042. for (var hNb = 0; hNb < holes.length; hNb++) {
  41043. hole = [];
  41044. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  41045. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  41046. }
  41047. polygonTriangulation.addHole(hole);
  41048. }
  41049. var polygon = polygonTriangulation.build(options.updatable, depth);
  41050. polygon.sideOrientation = options.sideOrientation;
  41051. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  41052. vertexData.applyToMesh(polygon, options.updatable);
  41053. return polygon;
  41054. };
  41055. ;
  41056. /**
  41057. * Creates an extruded polygon mesh, with depth in the Y direction.
  41058. * 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).
  41059. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  41060. */
  41061. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  41062. return MeshBuilder.CreatePolygon(name, options, scene);
  41063. };
  41064. ;
  41065. /**
  41066. * Creates a tube mesh.
  41067. * 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.
  41068. *
  41069. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  41070. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  41071. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  41072. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  41073. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  41074. * 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.
  41075. * It must return a radius value (positive float) :
  41076. * ```javascript
  41077. * var radiusFunction = function(i, distance) {
  41078. * // do things
  41079. * return radius; }
  41080. * ```
  41081. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  41082. * 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
  41083. * 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
  41084. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41085. * 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).
  41086. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41087. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41089. */
  41090. MeshBuilder.CreateTube = function (name, options, scene) {
  41091. var path = options.path;
  41092. var radius = options.radius || 1.0;
  41093. var tessellation = options.tessellation || 64 | 0;
  41094. var radiusFunction = options.radiusFunction;
  41095. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  41096. var invertUV = options.invertUV || false;
  41097. var updatable = options.updatable;
  41098. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41099. var instance = options.instance;
  41100. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  41101. // tube geometry
  41102. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  41103. var tangents = path3D.getTangents();
  41104. var normals = path3D.getNormals();
  41105. var distances = path3D.getDistances();
  41106. var pi2 = Math.PI * 2;
  41107. var step = pi2 / tessellation * arc;
  41108. var returnRadius = function () { return radius; };
  41109. var radiusFunctionFinal = radiusFunction || returnRadius;
  41110. var circlePath;
  41111. var rad;
  41112. var normal;
  41113. var rotated;
  41114. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  41115. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  41116. for (var i = 0; i < path.length; i++) {
  41117. rad = radiusFunctionFinal(i, distances[i]); // current radius
  41118. circlePath = Array(); // current circle array
  41119. normal = normals[i]; // current normal
  41120. for (var t = 0; t < tessellation; t++) {
  41121. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  41122. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  41123. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  41124. rotated.scaleInPlace(rad).addInPlace(path[i]);
  41125. circlePath[t] = rotated;
  41126. }
  41127. circlePaths[index] = circlePath;
  41128. index++;
  41129. }
  41130. // cap
  41131. var capPath = function (nbPoints, pathIndex) {
  41132. var pointCap = Array();
  41133. for (var i = 0; i < nbPoints; i++) {
  41134. pointCap.push(path[pathIndex]);
  41135. }
  41136. return pointCap;
  41137. };
  41138. switch (cap) {
  41139. case BABYLON.Mesh.NO_CAP:
  41140. break;
  41141. case BABYLON.Mesh.CAP_START:
  41142. circlePaths[0] = capPath(tessellation, 0);
  41143. circlePaths[1] = circlePaths[2].slice(0);
  41144. break;
  41145. case BABYLON.Mesh.CAP_END:
  41146. circlePaths[index] = circlePaths[index - 1].slice(0);
  41147. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  41148. break;
  41149. case BABYLON.Mesh.CAP_ALL:
  41150. circlePaths[0] = capPath(tessellation, 0);
  41151. circlePaths[1] = circlePaths[2].slice(0);
  41152. circlePaths[index] = circlePaths[index - 1].slice(0);
  41153. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  41154. break;
  41155. default:
  41156. break;
  41157. }
  41158. return circlePaths;
  41159. };
  41160. var path3D;
  41161. var pathArray;
  41162. if (instance) {
  41163. var arc = options.arc || instance.arc;
  41164. path3D = (instance.path3D).update(path);
  41165. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  41166. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  41167. instance.path3D = path3D;
  41168. instance.pathArray = pathArray;
  41169. instance.arc = arc;
  41170. return instance;
  41171. }
  41172. // tube creation
  41173. path3D = new BABYLON.Path3D(path);
  41174. var newPathArray = new Array();
  41175. cap = (cap < 0 || cap > 3) ? 0 : cap;
  41176. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  41177. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  41178. tube.pathArray = pathArray;
  41179. tube.path3D = path3D;
  41180. tube.tessellation = tessellation;
  41181. tube.cap = cap;
  41182. tube.arc = options.arc;
  41183. return tube;
  41184. };
  41185. /**
  41186. * Creates a polyhedron mesh.
  41187. *
  41188. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  41189. * 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
  41190. * to choose the wanted type.
  41191. * The parameter `size` (positive float, default 1) sets the polygon size.
  41192. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  41193. * 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`.
  41194. * 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
  41195. * 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)`).
  41196. * 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
  41197. * 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.
  41198. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41199. * 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).
  41200. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41201. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41202. */
  41203. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  41204. var polyhedron = new BABYLON.Mesh(name, scene);
  41205. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41206. polyhedron.sideOrientation = options.sideOrientation;
  41207. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  41208. vertexData.applyToMesh(polyhedron, options.updatable);
  41209. return polyhedron;
  41210. };
  41211. /**
  41212. * Creates a decal mesh.
  41213. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  41214. * 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.
  41215. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  41216. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  41217. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  41218. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  41219. */
  41220. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  41221. var indices = sourceMesh.getIndices();
  41222. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41223. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41224. var position = options.position || BABYLON.Vector3.Zero();
  41225. var normal = options.normal || BABYLON.Vector3.Up();
  41226. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  41227. var angle = options.angle || 0;
  41228. // Getting correct rotation
  41229. if (!normal) {
  41230. var target = new BABYLON.Vector3(0, 0, 1);
  41231. var camera = sourceMesh.getScene().activeCamera;
  41232. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  41233. normal = camera.globalPosition.subtract(cameraWorldTarget);
  41234. }
  41235. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  41236. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  41237. var pitch = Math.atan2(normal.y, len);
  41238. // Matrix
  41239. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  41240. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  41241. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  41242. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  41243. var vertexData = new BABYLON.VertexData();
  41244. vertexData.indices = [];
  41245. vertexData.positions = [];
  41246. vertexData.normals = [];
  41247. vertexData.uvs = [];
  41248. var currentVertexDataIndex = 0;
  41249. var extractDecalVector3 = function (indexId) {
  41250. var vertexId = indices[indexId];
  41251. var result = new BABYLON.PositionNormalVertex();
  41252. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  41253. // Send vector to decal local world
  41254. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  41255. // Get normal
  41256. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  41257. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  41258. return result;
  41259. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  41260. var clip = function (vertices, axis) {
  41261. if (vertices.length === 0) {
  41262. return vertices;
  41263. }
  41264. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  41265. var clipVertices = function (v0, v1) {
  41266. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  41267. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  41268. };
  41269. var result = new Array();
  41270. for (var index = 0; index < vertices.length; index += 3) {
  41271. var v1Out;
  41272. var v2Out;
  41273. var v3Out;
  41274. var total = 0;
  41275. var nV1, nV2, nV3, nV4;
  41276. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  41277. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  41278. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  41279. v1Out = d1 > 0;
  41280. v2Out = d2 > 0;
  41281. v3Out = d3 > 0;
  41282. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  41283. switch (total) {
  41284. case 0:
  41285. result.push(vertices[index]);
  41286. result.push(vertices[index + 1]);
  41287. result.push(vertices[index + 2]);
  41288. break;
  41289. case 1:
  41290. if (v1Out) {
  41291. nV1 = vertices[index + 1];
  41292. nV2 = vertices[index + 2];
  41293. nV3 = clipVertices(vertices[index], nV1);
  41294. nV4 = clipVertices(vertices[index], nV2);
  41295. }
  41296. if (v2Out) {
  41297. nV1 = vertices[index];
  41298. nV2 = vertices[index + 2];
  41299. nV3 = clipVertices(vertices[index + 1], nV1);
  41300. nV4 = clipVertices(vertices[index + 1], nV2);
  41301. result.push(nV3);
  41302. result.push(nV2.clone());
  41303. result.push(nV1.clone());
  41304. result.push(nV2.clone());
  41305. result.push(nV3.clone());
  41306. result.push(nV4);
  41307. break;
  41308. }
  41309. if (v3Out) {
  41310. nV1 = vertices[index];
  41311. nV2 = vertices[index + 1];
  41312. nV3 = clipVertices(vertices[index + 2], nV1);
  41313. nV4 = clipVertices(vertices[index + 2], nV2);
  41314. }
  41315. result.push(nV1.clone());
  41316. result.push(nV2.clone());
  41317. result.push(nV3);
  41318. result.push(nV4);
  41319. result.push(nV3.clone());
  41320. result.push(nV2.clone());
  41321. break;
  41322. case 2:
  41323. if (!v1Out) {
  41324. nV1 = vertices[index].clone();
  41325. nV2 = clipVertices(nV1, vertices[index + 1]);
  41326. nV3 = clipVertices(nV1, vertices[index + 2]);
  41327. result.push(nV1);
  41328. result.push(nV2);
  41329. result.push(nV3);
  41330. }
  41331. if (!v2Out) {
  41332. nV1 = vertices[index + 1].clone();
  41333. nV2 = clipVertices(nV1, vertices[index + 2]);
  41334. nV3 = clipVertices(nV1, vertices[index]);
  41335. result.push(nV1);
  41336. result.push(nV2);
  41337. result.push(nV3);
  41338. }
  41339. if (!v3Out) {
  41340. nV1 = vertices[index + 2].clone();
  41341. nV2 = clipVertices(nV1, vertices[index]);
  41342. nV3 = clipVertices(nV1, vertices[index + 1]);
  41343. result.push(nV1);
  41344. result.push(nV2);
  41345. result.push(nV3);
  41346. }
  41347. break;
  41348. case 3:
  41349. break;
  41350. }
  41351. }
  41352. return result;
  41353. };
  41354. for (var index = 0; index < indices.length; index += 3) {
  41355. var faceVertices = new Array();
  41356. faceVertices.push(extractDecalVector3(index));
  41357. faceVertices.push(extractDecalVector3(index + 1));
  41358. faceVertices.push(extractDecalVector3(index + 2));
  41359. // Clip
  41360. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  41361. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  41362. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  41363. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  41364. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  41365. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  41366. if (faceVertices.length === 0) {
  41367. continue;
  41368. }
  41369. // Add UVs and get back to world
  41370. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  41371. var vertex = faceVertices[vIndex];
  41372. //TODO check for Int32Array | Uint32Array | Uint16Array
  41373. vertexData.indices.push(currentVertexDataIndex);
  41374. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  41375. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  41376. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  41377. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  41378. currentVertexDataIndex++;
  41379. }
  41380. }
  41381. // Return mesh
  41382. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  41383. vertexData.applyToMesh(decal);
  41384. decal.position = position.clone();
  41385. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  41386. return decal;
  41387. };
  41388. // Privates
  41389. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  41390. // extrusion geometry
  41391. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  41392. var tangents = path3D.getTangents();
  41393. var normals = path3D.getNormals();
  41394. var binormals = path3D.getBinormals();
  41395. var distances = path3D.getDistances();
  41396. var angle = 0;
  41397. var returnScale = function () { return scale; };
  41398. var returnRotation = function () { return rotation; };
  41399. var rotate = custom ? rotateFunction : returnRotation;
  41400. var scl = custom ? scaleFunction : returnScale;
  41401. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  41402. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  41403. for (var i = 0; i < curve.length; i++) {
  41404. var shapePath = new Array();
  41405. var angleStep = rotate(i, distances[i]);
  41406. var scaleRatio = scl(i, distances[i]);
  41407. for (var p = 0; p < shape.length; p++) {
  41408. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  41409. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  41410. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  41411. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  41412. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  41413. shapePath[p] = rotated;
  41414. }
  41415. shapePaths[index] = shapePath;
  41416. angle += angleStep;
  41417. index++;
  41418. }
  41419. // cap
  41420. var capPath = function (shapePath) {
  41421. var pointCap = Array();
  41422. var barycenter = BABYLON.Vector3.Zero();
  41423. var i;
  41424. for (i = 0; i < shapePath.length; i++) {
  41425. barycenter.addInPlace(shapePath[i]);
  41426. }
  41427. barycenter.scaleInPlace(1.0 / shapePath.length);
  41428. for (i = 0; i < shapePath.length; i++) {
  41429. pointCap.push(barycenter);
  41430. }
  41431. return pointCap;
  41432. };
  41433. switch (cap) {
  41434. case BABYLON.Mesh.NO_CAP:
  41435. break;
  41436. case BABYLON.Mesh.CAP_START:
  41437. shapePaths[0] = capPath(shapePaths[2]);
  41438. shapePaths[1] = shapePaths[2];
  41439. break;
  41440. case BABYLON.Mesh.CAP_END:
  41441. shapePaths[index] = shapePaths[index - 1];
  41442. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41443. break;
  41444. case BABYLON.Mesh.CAP_ALL:
  41445. shapePaths[0] = capPath(shapePaths[2]);
  41446. shapePaths[1] = shapePaths[2];
  41447. shapePaths[index] = shapePaths[index - 1];
  41448. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41449. break;
  41450. default:
  41451. break;
  41452. }
  41453. return shapePaths;
  41454. };
  41455. var path3D;
  41456. var pathArray;
  41457. if (instance) {
  41458. path3D = (instance.path3D).update(curve);
  41459. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  41460. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  41461. return instance;
  41462. }
  41463. // extruded shape creation
  41464. path3D = new BABYLON.Path3D(curve);
  41465. var newShapePaths = new Array();
  41466. cap = (cap < 0 || cap > 3) ? 0 : cap;
  41467. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  41468. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  41469. extrudedGeneric.pathArray = pathArray;
  41470. extrudedGeneric.path3D = path3D;
  41471. extrudedGeneric.cap = cap;
  41472. return extrudedGeneric;
  41473. };
  41474. return MeshBuilder;
  41475. }());
  41476. BABYLON.MeshBuilder = MeshBuilder;
  41477. })(BABYLON || (BABYLON = {}));
  41478. //# sourceMappingURL=babylon.meshBuilder.js.map
  41479. var BABYLON;
  41480. (function (BABYLON) {
  41481. var AudioEngine = (function () {
  41482. function AudioEngine() {
  41483. this._audioContext = null;
  41484. this._audioContextInitialized = false;
  41485. this.canUseWebAudio = false;
  41486. this.WarnedWebAudioUnsupported = false;
  41487. this.unlocked = false;
  41488. this.isMP3supported = false;
  41489. this.isOGGsupported = false;
  41490. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  41491. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  41492. this.canUseWebAudio = true;
  41493. }
  41494. var audioElem = document.createElement('audio');
  41495. try {
  41496. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  41497. this.isMP3supported = true;
  41498. }
  41499. }
  41500. catch (e) {
  41501. // protect error during capability check.
  41502. }
  41503. try {
  41504. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  41505. this.isOGGsupported = true;
  41506. }
  41507. }
  41508. catch (e) {
  41509. // protect error during capability check.
  41510. }
  41511. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  41512. this._unlockiOSaudio();
  41513. }
  41514. else {
  41515. this.unlocked = true;
  41516. }
  41517. }
  41518. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  41519. get: function () {
  41520. if (!this._audioContextInitialized) {
  41521. this._initializeAudioContext();
  41522. }
  41523. return this._audioContext;
  41524. },
  41525. enumerable: true,
  41526. configurable: true
  41527. });
  41528. AudioEngine.prototype._unlockiOSaudio = function () {
  41529. var _this = this;
  41530. var unlockaudio = function () {
  41531. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  41532. var source = _this.audioContext.createBufferSource();
  41533. source.buffer = buffer;
  41534. source.connect(_this.audioContext.destination);
  41535. source.start(0);
  41536. setTimeout(function () {
  41537. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  41538. _this.unlocked = true;
  41539. window.removeEventListener('touchend', unlockaudio, false);
  41540. if (_this.onAudioUnlocked) {
  41541. _this.onAudioUnlocked();
  41542. }
  41543. }
  41544. }, 0);
  41545. };
  41546. window.addEventListener('touchend', unlockaudio, false);
  41547. };
  41548. AudioEngine.prototype._initializeAudioContext = function () {
  41549. try {
  41550. if (this.canUseWebAudio) {
  41551. this._audioContext = new AudioContext();
  41552. // create a global volume gain node
  41553. this.masterGain = this._audioContext.createGain();
  41554. this.masterGain.gain.value = 1;
  41555. this.masterGain.connect(this._audioContext.destination);
  41556. this._audioContextInitialized = true;
  41557. }
  41558. }
  41559. catch (e) {
  41560. this.canUseWebAudio = false;
  41561. BABYLON.Tools.Error("Web Audio: " + e.message);
  41562. }
  41563. };
  41564. AudioEngine.prototype.dispose = function () {
  41565. if (this.canUseWebAudio && this._audioContextInitialized) {
  41566. if (this._connectedAnalyser) {
  41567. this._connectedAnalyser.stopDebugCanvas();
  41568. this._connectedAnalyser.dispose();
  41569. this.masterGain.disconnect();
  41570. this.masterGain.connect(this._audioContext.destination);
  41571. this._connectedAnalyser = null;
  41572. }
  41573. this.masterGain.gain.value = 1;
  41574. }
  41575. this.WarnedWebAudioUnsupported = false;
  41576. };
  41577. AudioEngine.prototype.getGlobalVolume = function () {
  41578. if (this.canUseWebAudio && this._audioContextInitialized) {
  41579. return this.masterGain.gain.value;
  41580. }
  41581. else {
  41582. return -1;
  41583. }
  41584. };
  41585. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  41586. if (this.canUseWebAudio && this._audioContextInitialized) {
  41587. this.masterGain.gain.value = newVolume;
  41588. }
  41589. };
  41590. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  41591. if (this._connectedAnalyser) {
  41592. this._connectedAnalyser.stopDebugCanvas();
  41593. }
  41594. if (this.canUseWebAudio && this._audioContextInitialized) {
  41595. this._connectedAnalyser = analyser;
  41596. this.masterGain.disconnect();
  41597. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  41598. }
  41599. };
  41600. return AudioEngine;
  41601. }());
  41602. BABYLON.AudioEngine = AudioEngine;
  41603. })(BABYLON || (BABYLON = {}));
  41604. //# sourceMappingURL=babylon.audioEngine.js.map
  41605. var BABYLON;
  41606. (function (BABYLON) {
  41607. var Sound = (function () {
  41608. /**
  41609. * Create a sound and attach it to a scene
  41610. * @param name Name of your sound
  41611. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  41612. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  41613. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  41614. */
  41615. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  41616. var _this = this;
  41617. this.autoplay = false;
  41618. this.loop = false;
  41619. this.useCustomAttenuation = false;
  41620. this.spatialSound = false;
  41621. this.refDistance = 1;
  41622. this.rolloffFactor = 1;
  41623. this.maxDistance = 100;
  41624. this.distanceModel = "linear";
  41625. this._panningModel = "equalpower";
  41626. this._playbackRate = 1;
  41627. this._streaming = false;
  41628. this._startTime = 0;
  41629. this._startOffset = 0;
  41630. this._position = BABYLON.Vector3.Zero();
  41631. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  41632. this._volume = 1;
  41633. this._isLoaded = false;
  41634. this._isReadyToPlay = false;
  41635. this.isPlaying = false;
  41636. this.isPaused = false;
  41637. this._isDirectional = false;
  41638. // Used if you'd like to create a directional sound.
  41639. // If not set, the sound will be omnidirectional
  41640. this._coneInnerAngle = 360;
  41641. this._coneOuterAngle = 360;
  41642. this._coneOuterGain = 0;
  41643. this._isOutputConnected = false;
  41644. this._urlType = "Unknown";
  41645. this.name = name;
  41646. this._scene = scene;
  41647. this._readyToPlayCallback = readyToPlayCallback;
  41648. // Default custom attenuation function is a linear attenuation
  41649. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  41650. if (currentDistance < maxDistance) {
  41651. return currentVolume * (1 - currentDistance / maxDistance);
  41652. }
  41653. else {
  41654. return 0;
  41655. }
  41656. };
  41657. if (options) {
  41658. this.autoplay = options.autoplay || false;
  41659. this.loop = options.loop || false;
  41660. // if volume === 0, we need another way to check this option
  41661. if (options.volume !== undefined) {
  41662. this._volume = options.volume;
  41663. }
  41664. this.spatialSound = options.spatialSound || false;
  41665. this.maxDistance = options.maxDistance || 100;
  41666. this.useCustomAttenuation = options.useCustomAttenuation || false;
  41667. this.rolloffFactor = options.rolloffFactor || 1;
  41668. this.refDistance = options.refDistance || 1;
  41669. this.distanceModel = options.distanceModel || "linear";
  41670. this._playbackRate = options.playbackRate || 1;
  41671. this._streaming = options.streaming || false;
  41672. }
  41673. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41674. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  41675. this._soundGain.gain.value = this._volume;
  41676. this._inputAudioNode = this._soundGain;
  41677. this._ouputAudioNode = this._soundGain;
  41678. if (this.spatialSound) {
  41679. this._createSpatialParameters();
  41680. }
  41681. this._scene.mainSoundTrack.AddSound(this);
  41682. var validParameter = true;
  41683. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  41684. if (urlOrArrayBuffer) {
  41685. if (typeof (urlOrArrayBuffer) === "string")
  41686. this._urlType = "String";
  41687. if (Array.isArray(urlOrArrayBuffer))
  41688. this._urlType = "Array";
  41689. if (urlOrArrayBuffer instanceof ArrayBuffer)
  41690. this._urlType = "ArrayBuffer";
  41691. var urls = [];
  41692. var codecSupportedFound = false;
  41693. switch (this._urlType) {
  41694. case "ArrayBuffer":
  41695. if (urlOrArrayBuffer.byteLength > 0) {
  41696. codecSupportedFound = true;
  41697. this._soundLoaded(urlOrArrayBuffer);
  41698. }
  41699. break;
  41700. case "String":
  41701. urls.push(urlOrArrayBuffer);
  41702. case "Array":
  41703. if (urls.length === 0)
  41704. urls = urlOrArrayBuffer;
  41705. // If we found a supported format, we load it immediately and stop the loop
  41706. for (var i = 0; i < urls.length; i++) {
  41707. var url = urls[i];
  41708. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  41709. codecSupportedFound = true;
  41710. }
  41711. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  41712. codecSupportedFound = true;
  41713. }
  41714. if (url.indexOf(".wav", url.length - 4) !== -1) {
  41715. codecSupportedFound = true;
  41716. }
  41717. if (codecSupportedFound) {
  41718. // Loading sound using XHR2
  41719. if (!this._streaming) {
  41720. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  41721. }
  41722. else {
  41723. this._htmlAudioElement = new Audio(url);
  41724. this._htmlAudioElement.controls = false;
  41725. this._htmlAudioElement.loop = this.loop;
  41726. this._htmlAudioElement.crossOrigin = "anonymous";
  41727. this._htmlAudioElement.preload = "auto";
  41728. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  41729. _this._isReadyToPlay = true;
  41730. if (_this.autoplay) {
  41731. _this.play();
  41732. }
  41733. if (_this._readyToPlayCallback) {
  41734. _this._readyToPlayCallback();
  41735. }
  41736. });
  41737. document.body.appendChild(this._htmlAudioElement);
  41738. }
  41739. break;
  41740. }
  41741. }
  41742. break;
  41743. default:
  41744. validParameter = false;
  41745. break;
  41746. }
  41747. if (!validParameter) {
  41748. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  41749. }
  41750. else {
  41751. if (!codecSupportedFound) {
  41752. this._isReadyToPlay = true;
  41753. // Simulating a ready to play event to avoid breaking code path
  41754. if (this._readyToPlayCallback) {
  41755. window.setTimeout(function () {
  41756. _this._readyToPlayCallback();
  41757. }, 1000);
  41758. }
  41759. }
  41760. }
  41761. }
  41762. }
  41763. else {
  41764. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  41765. this._scene.mainSoundTrack.AddSound(this);
  41766. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  41767. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  41768. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  41769. }
  41770. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  41771. if (this._readyToPlayCallback) {
  41772. window.setTimeout(function () {
  41773. _this._readyToPlayCallback();
  41774. }, 1000);
  41775. }
  41776. }
  41777. }
  41778. Sound.prototype.dispose = function () {
  41779. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  41780. if (this.isPlaying) {
  41781. this.stop();
  41782. }
  41783. this._isReadyToPlay = false;
  41784. if (this.soundTrackId === -1) {
  41785. this._scene.mainSoundTrack.RemoveSound(this);
  41786. }
  41787. else {
  41788. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  41789. }
  41790. if (this._soundGain) {
  41791. this._soundGain.disconnect();
  41792. this._soundGain = null;
  41793. }
  41794. if (this._soundPanner) {
  41795. this._soundPanner.disconnect();
  41796. this._soundPanner = null;
  41797. }
  41798. if (this._soundSource) {
  41799. this._soundSource.disconnect();
  41800. this._soundSource = null;
  41801. }
  41802. this._audioBuffer = null;
  41803. if (this._htmlAudioElement) {
  41804. this._htmlAudioElement.pause();
  41805. this._htmlAudioElement.src = "";
  41806. document.body.removeChild(this._htmlAudioElement);
  41807. }
  41808. if (this._connectedMesh) {
  41809. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41810. this._connectedMesh = null;
  41811. }
  41812. }
  41813. };
  41814. Sound.prototype.isReady = function () {
  41815. return this._isReadyToPlay;
  41816. };
  41817. Sound.prototype._soundLoaded = function (audioData) {
  41818. var _this = this;
  41819. this._isLoaded = true;
  41820. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  41821. _this._audioBuffer = buffer;
  41822. _this._isReadyToPlay = true;
  41823. if (_this.autoplay) {
  41824. _this.play();
  41825. }
  41826. if (_this._readyToPlayCallback) {
  41827. _this._readyToPlayCallback();
  41828. }
  41829. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  41830. };
  41831. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  41832. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41833. this._audioBuffer = audioBuffer;
  41834. this._isReadyToPlay = true;
  41835. }
  41836. };
  41837. Sound.prototype.updateOptions = function (options) {
  41838. if (options) {
  41839. this.loop = options.loop || this.loop;
  41840. this.maxDistance = options.maxDistance || this.maxDistance;
  41841. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  41842. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  41843. this.refDistance = options.refDistance || this.refDistance;
  41844. this.distanceModel = options.distanceModel || this.distanceModel;
  41845. this._playbackRate = options.playbackRate || this._playbackRate;
  41846. this._updateSpatialParameters();
  41847. if (this.isPlaying) {
  41848. if (this._streaming) {
  41849. this._htmlAudioElement.playbackRate = this._playbackRate;
  41850. }
  41851. else {
  41852. this._soundSource.playbackRate.value = this._playbackRate;
  41853. }
  41854. }
  41855. }
  41856. };
  41857. Sound.prototype._createSpatialParameters = function () {
  41858. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41859. if (this._scene.headphone) {
  41860. this._panningModel = "HRTF";
  41861. }
  41862. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  41863. this._updateSpatialParameters();
  41864. this._soundPanner.connect(this._ouputAudioNode);
  41865. this._inputAudioNode = this._soundPanner;
  41866. }
  41867. };
  41868. Sound.prototype._updateSpatialParameters = function () {
  41869. if (this.spatialSound) {
  41870. if (this.useCustomAttenuation) {
  41871. // Tricks to disable in a way embedded Web Audio attenuation
  41872. this._soundPanner.distanceModel = "linear";
  41873. this._soundPanner.maxDistance = Number.MAX_VALUE;
  41874. this._soundPanner.refDistance = 1;
  41875. this._soundPanner.rolloffFactor = 1;
  41876. this._soundPanner.panningModel = this._panningModel;
  41877. }
  41878. else {
  41879. this._soundPanner.distanceModel = this.distanceModel;
  41880. this._soundPanner.maxDistance = this.maxDistance;
  41881. this._soundPanner.refDistance = this.refDistance;
  41882. this._soundPanner.rolloffFactor = this.rolloffFactor;
  41883. this._soundPanner.panningModel = this._panningModel;
  41884. }
  41885. }
  41886. };
  41887. Sound.prototype.switchPanningModelToHRTF = function () {
  41888. this._panningModel = "HRTF";
  41889. this._switchPanningModel();
  41890. };
  41891. Sound.prototype.switchPanningModelToEqualPower = function () {
  41892. this._panningModel = "equalpower";
  41893. this._switchPanningModel();
  41894. };
  41895. Sound.prototype._switchPanningModel = function () {
  41896. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41897. this._soundPanner.panningModel = this._panningModel;
  41898. }
  41899. };
  41900. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  41901. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41902. if (this._isOutputConnected) {
  41903. this._ouputAudioNode.disconnect();
  41904. }
  41905. this._ouputAudioNode.connect(soundTrackAudioNode);
  41906. this._isOutputConnected = true;
  41907. }
  41908. };
  41909. /**
  41910. * Transform this sound into a directional source
  41911. * @param coneInnerAngle Size of the inner cone in degree
  41912. * @param coneOuterAngle Size of the outer cone in degree
  41913. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  41914. */
  41915. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  41916. if (coneOuterAngle < coneInnerAngle) {
  41917. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  41918. return;
  41919. }
  41920. this._coneInnerAngle = coneInnerAngle;
  41921. this._coneOuterAngle = coneOuterAngle;
  41922. this._coneOuterGain = coneOuterGain;
  41923. this._isDirectional = true;
  41924. if (this.isPlaying && this.loop) {
  41925. this.stop();
  41926. this.play();
  41927. }
  41928. };
  41929. Sound.prototype.setPosition = function (newPosition) {
  41930. this._position = newPosition;
  41931. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41932. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  41933. }
  41934. };
  41935. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  41936. this._localDirection = newLocalDirection;
  41937. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  41938. this._updateDirection();
  41939. }
  41940. };
  41941. Sound.prototype._updateDirection = function () {
  41942. var mat = this._connectedMesh.getWorldMatrix();
  41943. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  41944. direction.normalize();
  41945. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  41946. };
  41947. Sound.prototype.updateDistanceFromListener = function () {
  41948. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  41949. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  41950. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  41951. }
  41952. };
  41953. Sound.prototype.setAttenuationFunction = function (callback) {
  41954. this._customAttenuationFunction = callback;
  41955. };
  41956. /**
  41957. * Play the sound
  41958. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  41959. * @param offset (optional) Start the sound setting it at a specific time
  41960. */
  41961. Sound.prototype.play = function (time, offset) {
  41962. var _this = this;
  41963. if (this._isReadyToPlay && this._scene.audioEnabled) {
  41964. try {
  41965. if (this._startOffset < 0) {
  41966. time = -this._startOffset;
  41967. this._startOffset = 0;
  41968. }
  41969. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  41970. if (!this._soundSource || !this._streamingSource) {
  41971. if (this.spatialSound) {
  41972. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  41973. if (this._isDirectional) {
  41974. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  41975. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  41976. this._soundPanner.coneOuterGain = this._coneOuterGain;
  41977. if (this._connectedMesh) {
  41978. this._updateDirection();
  41979. }
  41980. else {
  41981. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  41982. }
  41983. }
  41984. }
  41985. }
  41986. if (this._streaming) {
  41987. if (!this._streamingSource) {
  41988. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  41989. this._htmlAudioElement.onended = function () { _this._onended(); };
  41990. this._htmlAudioElement.playbackRate = this._playbackRate;
  41991. }
  41992. this._streamingSource.disconnect();
  41993. this._streamingSource.connect(this._inputAudioNode);
  41994. this._htmlAudioElement.play();
  41995. }
  41996. else {
  41997. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  41998. this._soundSource.buffer = this._audioBuffer;
  41999. this._soundSource.connect(this._inputAudioNode);
  42000. this._soundSource.loop = this.loop;
  42001. this._soundSource.playbackRate.value = this._playbackRate;
  42002. this._soundSource.onended = function () { _this._onended(); };
  42003. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  42004. }
  42005. this._startTime = startTime;
  42006. this.isPlaying = true;
  42007. this.isPaused = false;
  42008. }
  42009. catch (ex) {
  42010. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  42011. }
  42012. }
  42013. };
  42014. Sound.prototype._onended = function () {
  42015. this.isPlaying = false;
  42016. if (this.onended) {
  42017. this.onended();
  42018. }
  42019. };
  42020. /**
  42021. * Stop the sound
  42022. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  42023. */
  42024. Sound.prototype.stop = function (time) {
  42025. if (this.isPlaying) {
  42026. if (this._streaming) {
  42027. this._htmlAudioElement.pause();
  42028. // Test needed for Firefox or it will generate an Invalid State Error
  42029. if (this._htmlAudioElement.currentTime > 0) {
  42030. this._htmlAudioElement.currentTime = 0;
  42031. }
  42032. }
  42033. else {
  42034. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42035. this._soundSource.stop(stopTime);
  42036. this._soundSource.onended = null;
  42037. if (!this.isPaused) {
  42038. this._startOffset = 0;
  42039. }
  42040. }
  42041. this.isPlaying = false;
  42042. }
  42043. };
  42044. Sound.prototype.pause = function () {
  42045. if (this.isPlaying) {
  42046. this.isPaused = true;
  42047. if (this._streaming) {
  42048. this._htmlAudioElement.pause();
  42049. }
  42050. else {
  42051. this.stop(0);
  42052. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  42053. }
  42054. }
  42055. };
  42056. Sound.prototype.setVolume = function (newVolume, time) {
  42057. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42058. if (time) {
  42059. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  42060. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  42061. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  42062. }
  42063. else {
  42064. this._soundGain.gain.value = newVolume;
  42065. }
  42066. }
  42067. this._volume = newVolume;
  42068. };
  42069. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  42070. this._playbackRate = newPlaybackRate;
  42071. if (this.isPlaying) {
  42072. if (this._streaming) {
  42073. this._htmlAudioElement.playbackRate = this._playbackRate;
  42074. }
  42075. else {
  42076. this._soundSource.playbackRate.value = this._playbackRate;
  42077. }
  42078. }
  42079. };
  42080. Sound.prototype.getVolume = function () {
  42081. return this._volume;
  42082. };
  42083. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  42084. var _this = this;
  42085. if (this._connectedMesh) {
  42086. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42087. this._registerFunc = null;
  42088. }
  42089. this._connectedMesh = meshToConnectTo;
  42090. if (!this.spatialSound) {
  42091. this.spatialSound = true;
  42092. this._createSpatialParameters();
  42093. if (this.isPlaying && this.loop) {
  42094. this.stop();
  42095. this.play();
  42096. }
  42097. }
  42098. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  42099. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  42100. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  42101. };
  42102. Sound.prototype.detachFromMesh = function () {
  42103. if (this._connectedMesh) {
  42104. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42105. this._registerFunc = null;
  42106. this._connectedMesh = null;
  42107. }
  42108. };
  42109. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  42110. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  42111. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  42112. this._updateDirection();
  42113. }
  42114. };
  42115. Sound.prototype.clone = function () {
  42116. var _this = this;
  42117. if (!this._streaming) {
  42118. var setBufferAndRun = function () {
  42119. if (_this._isReadyToPlay) {
  42120. clonedSound._audioBuffer = _this.getAudioBuffer();
  42121. clonedSound._isReadyToPlay = true;
  42122. if (clonedSound.autoplay) {
  42123. clonedSound.play();
  42124. }
  42125. }
  42126. else {
  42127. window.setTimeout(setBufferAndRun, 300);
  42128. }
  42129. };
  42130. var currentOptions = {
  42131. autoplay: this.autoplay, loop: this.loop,
  42132. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  42133. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  42134. refDistance: this.refDistance, distanceModel: this.distanceModel
  42135. };
  42136. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  42137. if (this.useCustomAttenuation) {
  42138. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  42139. }
  42140. clonedSound.setPosition(this._position);
  42141. clonedSound.setPlaybackRate(this._playbackRate);
  42142. setBufferAndRun();
  42143. return clonedSound;
  42144. }
  42145. else {
  42146. return null;
  42147. }
  42148. };
  42149. Sound.prototype.getAudioBuffer = function () {
  42150. return this._audioBuffer;
  42151. };
  42152. Sound.prototype.serialize = function () {
  42153. var serializationObject = {
  42154. name: this.name,
  42155. url: this.name,
  42156. autoplay: this.autoplay,
  42157. loop: this.loop,
  42158. volume: this._volume,
  42159. spatialSound: this.spatialSound,
  42160. maxDistance: this.maxDistance,
  42161. rolloffFactor: this.rolloffFactor,
  42162. refDistance: this.refDistance,
  42163. distanceModel: this.distanceModel,
  42164. playbackRate: this._playbackRate,
  42165. panningModel: this._panningModel,
  42166. soundTrackId: this.soundTrackId
  42167. };
  42168. if (this.spatialSound) {
  42169. if (this._connectedMesh)
  42170. serializationObject.connectedMeshId = this._connectedMesh.id;
  42171. serializationObject.position = this._position.asArray();
  42172. serializationObject.refDistance = this.refDistance;
  42173. serializationObject.distanceModel = this.distanceModel;
  42174. serializationObject.isDirectional = this._isDirectional;
  42175. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  42176. serializationObject.coneInnerAngle = this._coneInnerAngle;
  42177. serializationObject.coneOuterAngle = this._coneOuterAngle;
  42178. serializationObject.coneOuterGain = this._coneOuterGain;
  42179. }
  42180. return serializationObject;
  42181. };
  42182. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  42183. var soundName = parsedSound.name;
  42184. var soundUrl;
  42185. if (parsedSound.url) {
  42186. soundUrl = rootUrl + parsedSound.url;
  42187. }
  42188. else {
  42189. soundUrl = rootUrl + soundName;
  42190. }
  42191. var options = {
  42192. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  42193. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  42194. rolloffFactor: parsedSound.rolloffFactor,
  42195. refDistance: parsedSound.refDistance,
  42196. distanceModel: parsedSound.distanceModel,
  42197. playbackRate: parsedSound.playbackRate
  42198. };
  42199. var newSound;
  42200. if (!sourceSound) {
  42201. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  42202. scene._addPendingData(newSound);
  42203. }
  42204. else {
  42205. var setBufferAndRun = function () {
  42206. if (sourceSound._isReadyToPlay) {
  42207. newSound._audioBuffer = sourceSound.getAudioBuffer();
  42208. newSound._isReadyToPlay = true;
  42209. if (newSound.autoplay) {
  42210. newSound.play();
  42211. }
  42212. }
  42213. else {
  42214. window.setTimeout(setBufferAndRun, 300);
  42215. }
  42216. };
  42217. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  42218. setBufferAndRun();
  42219. }
  42220. if (parsedSound.position) {
  42221. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  42222. newSound.setPosition(soundPosition);
  42223. }
  42224. if (parsedSound.isDirectional) {
  42225. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  42226. if (parsedSound.localDirectionToMesh) {
  42227. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  42228. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  42229. }
  42230. }
  42231. if (parsedSound.connectedMeshId) {
  42232. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  42233. if (connectedMesh) {
  42234. newSound.attachToMesh(connectedMesh);
  42235. }
  42236. }
  42237. return newSound;
  42238. };
  42239. return Sound;
  42240. }());
  42241. BABYLON.Sound = Sound;
  42242. })(BABYLON || (BABYLON = {}));
  42243. //# sourceMappingURL=babylon.sound.js.map
  42244. var BABYLON;
  42245. (function (BABYLON) {
  42246. var SoundTrack = (function () {
  42247. function SoundTrack(scene, options) {
  42248. this.id = -1;
  42249. this._isMainTrack = false;
  42250. this._isInitialized = false;
  42251. this._scene = scene;
  42252. this.soundCollection = new Array();
  42253. this._options = options;
  42254. if (!this._isMainTrack) {
  42255. this._scene.soundTracks.push(this);
  42256. this.id = this._scene.soundTracks.length - 1;
  42257. }
  42258. }
  42259. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  42260. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42261. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  42262. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  42263. if (this._options) {
  42264. if (this._options.volume) {
  42265. this._outputAudioNode.gain.value = this._options.volume;
  42266. }
  42267. if (this._options.mainTrack) {
  42268. this._isMainTrack = this._options.mainTrack;
  42269. }
  42270. }
  42271. this._isInitialized = true;
  42272. }
  42273. };
  42274. SoundTrack.prototype.dispose = function () {
  42275. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42276. if (this._connectedAnalyser) {
  42277. this._connectedAnalyser.stopDebugCanvas();
  42278. }
  42279. while (this.soundCollection.length) {
  42280. this.soundCollection[0].dispose();
  42281. }
  42282. if (this._outputAudioNode) {
  42283. this._outputAudioNode.disconnect();
  42284. }
  42285. this._outputAudioNode = null;
  42286. }
  42287. };
  42288. SoundTrack.prototype.AddSound = function (sound) {
  42289. if (!this._isInitialized) {
  42290. this._initializeSoundTrackAudioGraph();
  42291. }
  42292. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42293. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  42294. }
  42295. if (sound.soundTrackId) {
  42296. if (sound.soundTrackId === -1) {
  42297. this._scene.mainSoundTrack.RemoveSound(sound);
  42298. }
  42299. else {
  42300. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  42301. }
  42302. }
  42303. this.soundCollection.push(sound);
  42304. sound.soundTrackId = this.id;
  42305. };
  42306. SoundTrack.prototype.RemoveSound = function (sound) {
  42307. var index = this.soundCollection.indexOf(sound);
  42308. if (index !== -1) {
  42309. this.soundCollection.splice(index, 1);
  42310. }
  42311. };
  42312. SoundTrack.prototype.setVolume = function (newVolume) {
  42313. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42314. this._outputAudioNode.gain.value = newVolume;
  42315. }
  42316. };
  42317. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  42318. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42319. for (var i = 0; i < this.soundCollection.length; i++) {
  42320. this.soundCollection[i].switchPanningModelToHRTF();
  42321. }
  42322. }
  42323. };
  42324. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  42325. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42326. for (var i = 0; i < this.soundCollection.length; i++) {
  42327. this.soundCollection[i].switchPanningModelToEqualPower();
  42328. }
  42329. }
  42330. };
  42331. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  42332. if (this._connectedAnalyser) {
  42333. this._connectedAnalyser.stopDebugCanvas();
  42334. }
  42335. this._connectedAnalyser = analyser;
  42336. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42337. this._outputAudioNode.disconnect();
  42338. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  42339. }
  42340. };
  42341. return SoundTrack;
  42342. }());
  42343. BABYLON.SoundTrack = SoundTrack;
  42344. })(BABYLON || (BABYLON = {}));
  42345. //# sourceMappingURL=babylon.soundtrack.js.map
  42346. var BABYLON;
  42347. (function (BABYLON) {
  42348. var Analyser = (function () {
  42349. function Analyser(scene) {
  42350. this.SMOOTHING = 0.75;
  42351. this.FFT_SIZE = 512;
  42352. this.BARGRAPHAMPLITUDE = 256;
  42353. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  42354. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  42355. this._scene = scene;
  42356. this._audioEngine = BABYLON.Engine.audioEngine;
  42357. if (this._audioEngine.canUseWebAudio) {
  42358. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  42359. this._webAudioAnalyser.minDecibels = -140;
  42360. this._webAudioAnalyser.maxDecibels = 0;
  42361. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42362. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42363. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  42364. }
  42365. }
  42366. Analyser.prototype.getFrequencyBinCount = function () {
  42367. if (this._audioEngine.canUseWebAudio) {
  42368. return this._webAudioAnalyser.frequencyBinCount;
  42369. }
  42370. else {
  42371. return 0;
  42372. }
  42373. };
  42374. Analyser.prototype.getByteFrequencyData = function () {
  42375. if (this._audioEngine.canUseWebAudio) {
  42376. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42377. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42378. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  42379. }
  42380. return this._byteFreqs;
  42381. };
  42382. Analyser.prototype.getByteTimeDomainData = function () {
  42383. if (this._audioEngine.canUseWebAudio) {
  42384. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42385. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42386. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  42387. }
  42388. return this._byteTime;
  42389. };
  42390. Analyser.prototype.getFloatFrequencyData = function () {
  42391. if (this._audioEngine.canUseWebAudio) {
  42392. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42393. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42394. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  42395. }
  42396. return this._floatFreqs;
  42397. };
  42398. Analyser.prototype.drawDebugCanvas = function () {
  42399. var _this = this;
  42400. if (this._audioEngine.canUseWebAudio) {
  42401. if (!this._debugCanvas) {
  42402. this._debugCanvas = document.createElement("canvas");
  42403. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  42404. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  42405. this._debugCanvas.style.position = "absolute";
  42406. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  42407. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  42408. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  42409. document.body.appendChild(this._debugCanvas);
  42410. this._registerFunc = function () {
  42411. _this.drawDebugCanvas();
  42412. };
  42413. this._scene.registerBeforeRender(this._registerFunc);
  42414. }
  42415. if (this._registerFunc) {
  42416. var workingArray = this.getByteFrequencyData();
  42417. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  42418. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  42419. // Draw the frequency domain chart.
  42420. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  42421. var value = workingArray[i];
  42422. var percent = value / this.BARGRAPHAMPLITUDE;
  42423. var height = this.DEBUGCANVASSIZE.height * percent;
  42424. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  42425. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  42426. var hue = i / this.getFrequencyBinCount() * 360;
  42427. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  42428. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  42429. }
  42430. }
  42431. }
  42432. };
  42433. Analyser.prototype.stopDebugCanvas = function () {
  42434. if (this._debugCanvas) {
  42435. this._scene.unregisterBeforeRender(this._registerFunc);
  42436. this._registerFunc = null;
  42437. document.body.removeChild(this._debugCanvas);
  42438. this._debugCanvas = null;
  42439. this._debugCanvasContext = null;
  42440. }
  42441. };
  42442. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  42443. if (this._audioEngine.canUseWebAudio) {
  42444. inputAudioNode.connect(this._webAudioAnalyser);
  42445. this._webAudioAnalyser.connect(outputAudioNode);
  42446. }
  42447. };
  42448. Analyser.prototype.dispose = function () {
  42449. if (this._audioEngine.canUseWebAudio) {
  42450. this._webAudioAnalyser.disconnect();
  42451. }
  42452. };
  42453. return Analyser;
  42454. }());
  42455. BABYLON.Analyser = Analyser;
  42456. })(BABYLON || (BABYLON = {}));
  42457. //# sourceMappingURL=babylon.analyser.js.map
  42458. var BABYLON;
  42459. (function (BABYLON) {
  42460. var CubeTexture = (function (_super) {
  42461. __extends(CubeTexture, _super);
  42462. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  42463. if (onLoad === void 0) { onLoad = null; }
  42464. if (onError === void 0) { onError = null; }
  42465. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  42466. var _this = _super.call(this, scene) || this;
  42467. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  42468. _this.name = rootUrl;
  42469. _this.url = rootUrl;
  42470. _this._noMipmap = noMipmap;
  42471. _this.hasAlpha = false;
  42472. _this._format = format;
  42473. if (!rootUrl && !files) {
  42474. return _this;
  42475. }
  42476. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  42477. if (!files) {
  42478. if (!extensions) {
  42479. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  42480. }
  42481. files = [];
  42482. for (var index = 0; index < extensions.length; index++) {
  42483. files.push(rootUrl + extensions[index]);
  42484. }
  42485. _this._extensions = extensions;
  42486. }
  42487. _this._files = files;
  42488. if (!_this._texture) {
  42489. if (!scene.useDelayedTextureLoading) {
  42490. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  42491. }
  42492. else {
  42493. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  42494. }
  42495. }
  42496. else if (onLoad) {
  42497. if (_this._texture.isReady) {
  42498. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  42499. }
  42500. else {
  42501. _this._texture.onLoadedCallbacks.push(onLoad);
  42502. }
  42503. }
  42504. _this.isCube = true;
  42505. _this._textureMatrix = BABYLON.Matrix.Identity();
  42506. return _this;
  42507. }
  42508. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  42509. return new CubeTexture("", scene, null, noMipmap, files);
  42510. };
  42511. // Methods
  42512. CubeTexture.prototype.delayLoad = function () {
  42513. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  42514. return;
  42515. }
  42516. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  42517. this._texture = this._getFromCache(this.url, this._noMipmap);
  42518. if (!this._texture) {
  42519. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  42520. }
  42521. };
  42522. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  42523. return this._textureMatrix;
  42524. };
  42525. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  42526. var texture = BABYLON.SerializationHelper.Parse(function () {
  42527. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  42528. }, parsedTexture, scene);
  42529. // Animations
  42530. if (parsedTexture.animations) {
  42531. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  42532. var parsedAnimation = parsedTexture.animations[animationIndex];
  42533. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  42534. }
  42535. }
  42536. return texture;
  42537. };
  42538. CubeTexture.prototype.clone = function () {
  42539. var _this = this;
  42540. return BABYLON.SerializationHelper.Clone(function () {
  42541. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  42542. }, this);
  42543. };
  42544. return CubeTexture;
  42545. }(BABYLON.BaseTexture));
  42546. BABYLON.CubeTexture = CubeTexture;
  42547. })(BABYLON || (BABYLON = {}));
  42548. //# sourceMappingURL=babylon.cubeTexture.js.map
  42549. var BABYLON;
  42550. (function (BABYLON) {
  42551. var RenderTargetTexture = (function (_super) {
  42552. __extends(RenderTargetTexture, _super);
  42553. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  42554. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  42555. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  42556. if (isCube === void 0) { isCube = false; }
  42557. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42558. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  42559. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  42560. if (isMulti === void 0) { isMulti = false; }
  42561. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  42562. _this.isCube = isCube;
  42563. /**
  42564. * Use this list to define the list of mesh you want to render.
  42565. */
  42566. _this.renderList = new Array();
  42567. _this.renderParticles = true;
  42568. _this.renderSprites = false;
  42569. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  42570. // Events
  42571. /**
  42572. * An event triggered when the texture is unbind.
  42573. * @type {BABYLON.Observable}
  42574. */
  42575. _this.onAfterUnbindObservable = new BABYLON.Observable();
  42576. /**
  42577. * An event triggered before rendering the texture
  42578. * @type {BABYLON.Observable}
  42579. */
  42580. _this.onBeforeRenderObservable = new BABYLON.Observable();
  42581. /**
  42582. * An event triggered after rendering the texture
  42583. * @type {BABYLON.Observable}
  42584. */
  42585. _this.onAfterRenderObservable = new BABYLON.Observable();
  42586. /**
  42587. * An event triggered after the texture clear
  42588. * @type {BABYLON.Observable}
  42589. */
  42590. _this.onClearObservable = new BABYLON.Observable();
  42591. _this._currentRefreshId = -1;
  42592. _this._refreshRate = 1;
  42593. _this._samples = 1;
  42594. _this.name = name;
  42595. _this.isRenderTarget = true;
  42596. _this._size = size;
  42597. _this._generateMipMaps = generateMipMaps;
  42598. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  42599. // Rendering groups
  42600. _this._renderingManager = new BABYLON.RenderingManager(scene);
  42601. if (isMulti) {
  42602. return _this;
  42603. }
  42604. _this._renderTargetOptions = {
  42605. generateMipMaps: generateMipMaps,
  42606. type: type,
  42607. samplingMode: samplingMode,
  42608. generateDepthBuffer: generateDepthBuffer,
  42609. generateStencilBuffer: generateStencilBuffer
  42610. };
  42611. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  42612. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42613. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42614. }
  42615. if (isCube) {
  42616. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  42617. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  42618. _this._textureMatrix = BABYLON.Matrix.Identity();
  42619. }
  42620. else {
  42621. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  42622. }
  42623. return _this;
  42624. }
  42625. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  42626. get: function () {
  42627. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  42628. },
  42629. enumerable: true,
  42630. configurable: true
  42631. });
  42632. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  42633. get: function () {
  42634. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  42635. },
  42636. enumerable: true,
  42637. configurable: true
  42638. });
  42639. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  42640. get: function () {
  42641. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  42642. },
  42643. enumerable: true,
  42644. configurable: true
  42645. });
  42646. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  42647. set: function (callback) {
  42648. if (this._onAfterUnbindObserver) {
  42649. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  42650. }
  42651. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  42652. },
  42653. enumerable: true,
  42654. configurable: true
  42655. });
  42656. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  42657. set: function (callback) {
  42658. if (this._onBeforeRenderObserver) {
  42659. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  42660. }
  42661. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  42662. },
  42663. enumerable: true,
  42664. configurable: true
  42665. });
  42666. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  42667. set: function (callback) {
  42668. if (this._onAfterRenderObserver) {
  42669. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  42670. }
  42671. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  42672. },
  42673. enumerable: true,
  42674. configurable: true
  42675. });
  42676. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  42677. set: function (callback) {
  42678. if (this._onClearObserver) {
  42679. this.onClearObservable.remove(this._onClearObserver);
  42680. }
  42681. this._onClearObserver = this.onClearObservable.add(callback);
  42682. },
  42683. enumerable: true,
  42684. configurable: true
  42685. });
  42686. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  42687. get: function () {
  42688. return this._renderTargetOptions;
  42689. },
  42690. enumerable: true,
  42691. configurable: true
  42692. });
  42693. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  42694. get: function () {
  42695. return this._samples;
  42696. },
  42697. set: function (value) {
  42698. if (this._samples === value) {
  42699. return;
  42700. }
  42701. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  42702. },
  42703. enumerable: true,
  42704. configurable: true
  42705. });
  42706. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  42707. this._currentRefreshId = -1;
  42708. };
  42709. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  42710. get: function () {
  42711. return this._refreshRate;
  42712. },
  42713. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  42714. set: function (value) {
  42715. this._refreshRate = value;
  42716. this.resetRefreshCounter();
  42717. },
  42718. enumerable: true,
  42719. configurable: true
  42720. });
  42721. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  42722. if (!this._postProcessManager) {
  42723. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  42724. this._postProcesses = new Array();
  42725. }
  42726. this._postProcesses.push(postProcess);
  42727. this._postProcesses[0].autoClear = false;
  42728. };
  42729. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  42730. if (!this._postProcesses) {
  42731. return;
  42732. }
  42733. if (dispose) {
  42734. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  42735. var postProcess = _a[_i];
  42736. postProcess.dispose();
  42737. postProcess = null;
  42738. }
  42739. }
  42740. this._postProcesses = [];
  42741. };
  42742. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  42743. if (!this._postProcesses) {
  42744. return;
  42745. }
  42746. var index = this._postProcesses.indexOf(postProcess);
  42747. if (index === -1) {
  42748. return;
  42749. }
  42750. this._postProcesses.splice(index, 1);
  42751. if (this._postProcesses.length > 0) {
  42752. this._postProcesses[0].autoClear = false;
  42753. }
  42754. };
  42755. RenderTargetTexture.prototype._shouldRender = function () {
  42756. if (this._currentRefreshId === -1) {
  42757. this._currentRefreshId = 1;
  42758. return true;
  42759. }
  42760. if (this.refreshRate === this._currentRefreshId) {
  42761. this._currentRefreshId = 1;
  42762. return true;
  42763. }
  42764. this._currentRefreshId++;
  42765. return false;
  42766. };
  42767. RenderTargetTexture.prototype.isReady = function () {
  42768. if (!this.getScene().renderTargetsEnabled) {
  42769. return false;
  42770. }
  42771. return _super.prototype.isReady.call(this);
  42772. };
  42773. RenderTargetTexture.prototype.getRenderSize = function () {
  42774. return this._size;
  42775. };
  42776. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  42777. get: function () {
  42778. return true;
  42779. },
  42780. enumerable: true,
  42781. configurable: true
  42782. });
  42783. RenderTargetTexture.prototype.scale = function (ratio) {
  42784. var newSize = this._size * ratio;
  42785. this.resize(newSize);
  42786. };
  42787. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  42788. if (this.isCube) {
  42789. return this._textureMatrix;
  42790. }
  42791. return _super.prototype.getReflectionTextureMatrix.call(this);
  42792. };
  42793. RenderTargetTexture.prototype.resize = function (size) {
  42794. this.releaseInternalTexture();
  42795. if (this.isCube) {
  42796. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  42797. }
  42798. else {
  42799. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  42800. }
  42801. };
  42802. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  42803. var scene = this.getScene();
  42804. var engine = scene.getEngine();
  42805. if (this.useCameraPostProcesses !== undefined) {
  42806. useCameraPostProcess = this.useCameraPostProcesses;
  42807. }
  42808. if (this._waitingRenderList) {
  42809. this.renderList = [];
  42810. for (var index = 0; index < this._waitingRenderList.length; index++) {
  42811. var id = this._waitingRenderList[index];
  42812. this.renderList.push(scene.getMeshByID(id));
  42813. }
  42814. delete this._waitingRenderList;
  42815. }
  42816. // Is predicate defined?
  42817. if (this.renderListPredicate) {
  42818. this.renderList.splice(0); // Clear previous renderList
  42819. var sceneMeshes = this.getScene().meshes;
  42820. for (var index = 0; index < sceneMeshes.length; index++) {
  42821. var mesh = sceneMeshes[index];
  42822. if (this.renderListPredicate(mesh)) {
  42823. this.renderList.push(mesh);
  42824. }
  42825. }
  42826. }
  42827. if (this.renderList && this.renderList.length === 0) {
  42828. return;
  42829. }
  42830. // Set custom projection.
  42831. // Needs to be before binding to prevent changing the aspect ratio.
  42832. var camera;
  42833. if (this.activeCamera) {
  42834. camera = this.activeCamera;
  42835. engine.setViewport(this.activeCamera.viewport);
  42836. if (this.activeCamera !== scene.activeCamera) {
  42837. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  42838. }
  42839. }
  42840. else {
  42841. camera = scene.activeCamera;
  42842. engine.setViewport(scene.activeCamera.viewport);
  42843. }
  42844. // Prepare renderingManager
  42845. this._renderingManager.reset();
  42846. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  42847. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  42848. var sceneRenderId = scene.getRenderId();
  42849. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  42850. var mesh = currentRenderList[meshIndex];
  42851. if (mesh) {
  42852. if (!mesh.isReady()) {
  42853. // Reset _currentRefreshId
  42854. this.resetRefreshCounter();
  42855. continue;
  42856. }
  42857. mesh._preActivateForIntermediateRendering(sceneRenderId);
  42858. var isMasked = void 0;
  42859. if (!this.renderList) {
  42860. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  42861. }
  42862. else {
  42863. isMasked = false;
  42864. }
  42865. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  42866. mesh._activate(sceneRenderId);
  42867. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42868. var subMesh = mesh.subMeshes[subIndex];
  42869. scene._activeIndices.addCount(subMesh.indexCount, false);
  42870. this._renderingManager.dispatch(subMesh);
  42871. }
  42872. }
  42873. }
  42874. }
  42875. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  42876. var particleSystem = scene.particleSystems[particleIndex];
  42877. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  42878. continue;
  42879. }
  42880. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  42881. this._renderingManager.dispatchParticles(particleSystem);
  42882. }
  42883. }
  42884. if (this.isCube) {
  42885. for (var face = 0; face < 6; face++) {
  42886. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  42887. scene.incrementRenderId();
  42888. scene.resetCachedMaterial();
  42889. }
  42890. }
  42891. else {
  42892. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  42893. }
  42894. this.onAfterUnbindObservable.notifyObservers(this);
  42895. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  42896. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  42897. }
  42898. engine.setViewport(scene.activeCamera.viewport);
  42899. scene.resetCachedMaterial();
  42900. };
  42901. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  42902. var _this = this;
  42903. var scene = this.getScene();
  42904. var engine = scene.getEngine();
  42905. // Bind
  42906. if (this._postProcessManager) {
  42907. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  42908. }
  42909. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  42910. if (this.isCube) {
  42911. engine.bindFramebuffer(this._texture, faceIndex);
  42912. }
  42913. else {
  42914. engine.bindFramebuffer(this._texture);
  42915. }
  42916. }
  42917. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  42918. // Clear
  42919. if (this.onClearObservable.hasObservers()) {
  42920. this.onClearObservable.notifyObservers(engine);
  42921. }
  42922. else {
  42923. engine.clear(scene.clearColor, true, true, true);
  42924. }
  42925. if (!this._doNotChangeAspectRatio) {
  42926. scene.updateTransformMatrix(true);
  42927. }
  42928. // Render
  42929. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  42930. if (this._postProcessManager) {
  42931. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  42932. }
  42933. else if (useCameraPostProcess) {
  42934. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  42935. }
  42936. if (!this._doNotChangeAspectRatio) {
  42937. scene.updateTransformMatrix(true);
  42938. }
  42939. // Dump ?
  42940. if (dumpForDebug) {
  42941. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  42942. }
  42943. // Unbind
  42944. if (!this.isCube || faceIndex === 5) {
  42945. if (this.isCube) {
  42946. if (faceIndex === 5) {
  42947. engine.generateMipMapsForCubemap(this._texture);
  42948. }
  42949. }
  42950. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  42951. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  42952. });
  42953. }
  42954. else {
  42955. this.onAfterRenderObservable.notifyObservers(faceIndex);
  42956. }
  42957. };
  42958. /**
  42959. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  42960. * This allowed control for front to back rendering or reversly depending of the special needs.
  42961. *
  42962. * @param renderingGroupId The rendering group id corresponding to its index
  42963. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  42964. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  42965. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  42966. */
  42967. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  42968. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  42969. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  42970. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  42971. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  42972. };
  42973. /**
  42974. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  42975. *
  42976. * @param renderingGroupId The rendering group id corresponding to its index
  42977. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  42978. */
  42979. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  42980. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  42981. };
  42982. RenderTargetTexture.prototype.clone = function () {
  42983. var textureSize = this.getSize();
  42984. 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);
  42985. // Base texture
  42986. newTexture.hasAlpha = this.hasAlpha;
  42987. newTexture.level = this.level;
  42988. // RenderTarget Texture
  42989. newTexture.coordinatesMode = this.coordinatesMode;
  42990. newTexture.renderList = this.renderList.slice(0);
  42991. return newTexture;
  42992. };
  42993. RenderTargetTexture.prototype.serialize = function () {
  42994. if (!this.name) {
  42995. return null;
  42996. }
  42997. var serializationObject = _super.prototype.serialize.call(this);
  42998. serializationObject.renderTargetSize = this.getRenderSize();
  42999. serializationObject.renderList = [];
  43000. for (var index = 0; index < this.renderList.length; index++) {
  43001. serializationObject.renderList.push(this.renderList[index].id);
  43002. }
  43003. return serializationObject;
  43004. };
  43005. RenderTargetTexture.prototype.dispose = function () {
  43006. if (this._postProcessManager) {
  43007. this._postProcessManager.dispose();
  43008. this._postProcessManager = null;
  43009. }
  43010. this.clearPostProcesses(true);
  43011. _super.prototype.dispose.call(this);
  43012. };
  43013. return RenderTargetTexture;
  43014. }(BABYLON.Texture));
  43015. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  43016. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  43017. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  43018. BABYLON.RenderTargetTexture = RenderTargetTexture;
  43019. })(BABYLON || (BABYLON = {}));
  43020. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  43021. var BABYLON;
  43022. (function (BABYLON) {
  43023. ;
  43024. var MultiRenderTarget = (function (_super) {
  43025. __extends(MultiRenderTarget, _super);
  43026. function MultiRenderTarget(name, size, count, scene, options) {
  43027. var _this = this;
  43028. options = options || {};
  43029. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  43030. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  43031. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  43032. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  43033. if (!_this.isSupported) {
  43034. _this.dispose();
  43035. return;
  43036. }
  43037. var types = [];
  43038. var samplingModes = [];
  43039. for (var i = 0; i < count; i++) {
  43040. if (options.types && options.types[i]) {
  43041. types.push(options.types[i]);
  43042. }
  43043. else {
  43044. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  43045. }
  43046. if (options.samplingModes && options.samplingModes[i]) {
  43047. samplingModes.push(options.samplingModes[i]);
  43048. }
  43049. else {
  43050. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43051. }
  43052. }
  43053. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  43054. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  43055. _this._count = count;
  43056. _this._size = size;
  43057. _this._multiRenderTargetOptions = {
  43058. samplingModes: samplingModes,
  43059. generateMipMaps: generateMipMaps,
  43060. generateDepthBuffer: generateDepthBuffer,
  43061. generateStencilBuffer: generateStencilBuffer,
  43062. generateDepthTexture: generateDepthTexture,
  43063. types: types,
  43064. textureCount: count
  43065. };
  43066. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  43067. _this._createInternalTextures();
  43068. return _this;
  43069. }
  43070. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  43071. get: function () {
  43072. var engine = this.getScene().getEngine();
  43073. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  43074. },
  43075. enumerable: true,
  43076. configurable: true
  43077. });
  43078. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  43079. get: function () {
  43080. return this._textures;
  43081. },
  43082. enumerable: true,
  43083. configurable: true
  43084. });
  43085. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  43086. get: function () {
  43087. return this._textures[this._textures.length - 1];
  43088. },
  43089. enumerable: true,
  43090. configurable: true
  43091. });
  43092. MultiRenderTarget.prototype._createInternalTextures = function () {
  43093. this._textures = [];
  43094. for (var i = 0; i < this._webGLTextures.length; i++) {
  43095. var texture = new BABYLON.Texture(null, this.getScene());
  43096. texture._texture = this._webGLTextures[i];
  43097. this._textures.push(texture);
  43098. }
  43099. // Keeps references to frame buffer and stencil/depth buffer
  43100. this._texture = this._webGLTextures[0];
  43101. };
  43102. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  43103. get: function () {
  43104. return this._samples;
  43105. },
  43106. set: function (value) {
  43107. if (this._samples === value) {
  43108. return;
  43109. }
  43110. for (var i = 0; i < this._webGLTextures.length; i++) {
  43111. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  43112. }
  43113. },
  43114. enumerable: true,
  43115. configurable: true
  43116. });
  43117. MultiRenderTarget.prototype.resize = function (size) {
  43118. this.releaseInternalTextures();
  43119. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  43120. this._createInternalTextures();
  43121. };
  43122. MultiRenderTarget.prototype.dispose = function () {
  43123. this.releaseInternalTextures();
  43124. _super.prototype.dispose.call(this);
  43125. };
  43126. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  43127. if (!this._webGLTextures) {
  43128. return;
  43129. }
  43130. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  43131. if (this._webGLTextures[i] !== undefined) {
  43132. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  43133. this._webGLTextures.splice(i, 1);
  43134. }
  43135. }
  43136. };
  43137. return MultiRenderTarget;
  43138. }(BABYLON.RenderTargetTexture));
  43139. BABYLON.MultiRenderTarget = MultiRenderTarget;
  43140. })(BABYLON || (BABYLON = {}));
  43141. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  43142. /// <reference path="babylon.renderTargetTexture.ts" />
  43143. var BABYLON;
  43144. (function (BABYLON) {
  43145. var MirrorTexture = (function (_super) {
  43146. __extends(MirrorTexture, _super);
  43147. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  43148. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43149. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  43150. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  43151. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  43152. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  43153. _this._transformMatrix = BABYLON.Matrix.Zero();
  43154. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  43155. _this._blurKernel = 0;
  43156. _this._blurRatio = 1.0;
  43157. _this.onBeforeRenderObservable.add(function () {
  43158. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  43159. _this._savedViewMatrix = scene.getViewMatrix();
  43160. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  43161. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  43162. scene.clipPlane = _this.mirrorPlane;
  43163. scene.getEngine().cullBackFaces = false;
  43164. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  43165. });
  43166. _this.onAfterRenderObservable.add(function () {
  43167. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  43168. scene.getEngine().cullBackFaces = true;
  43169. scene._mirroredCameraPosition = null;
  43170. delete scene.clipPlane;
  43171. });
  43172. return _this;
  43173. }
  43174. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  43175. get: function () {
  43176. return this._blurRatio;
  43177. },
  43178. set: function (value) {
  43179. if (this._blurRatio === value) {
  43180. return;
  43181. }
  43182. this._blurRatio = value;
  43183. this._preparePostProcesses();
  43184. },
  43185. enumerable: true,
  43186. configurable: true
  43187. });
  43188. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  43189. get: function () {
  43190. return this._blurKernel;
  43191. },
  43192. set: function (value) {
  43193. if (this._blurKernel === value) {
  43194. return;
  43195. }
  43196. this._blurKernel = value;
  43197. this._preparePostProcesses();
  43198. },
  43199. enumerable: true,
  43200. configurable: true
  43201. });
  43202. MirrorTexture.prototype._preparePostProcesses = function () {
  43203. this.clearPostProcesses(true);
  43204. if (this._blurKernel) {
  43205. var engine = this.getScene().getEngine();
  43206. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  43207. this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernel, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  43208. this._blurX.autoClear = false;
  43209. if (this._blurRatio === 1) {
  43210. this._blurX.outputTexture = this._texture;
  43211. }
  43212. else {
  43213. this._blurX.alwaysForcePOT = true;
  43214. }
  43215. this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernel, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  43216. this._blurY.autoClear = false;
  43217. this._blurY.alwaysForcePOT = true;
  43218. if (this._blurRatio !== 1) {
  43219. this._blurY.alwaysForcePOT = true;
  43220. }
  43221. this.addPostProcess(this._blurX);
  43222. this.addPostProcess(this._blurY);
  43223. }
  43224. };
  43225. MirrorTexture.prototype.clone = function () {
  43226. var textureSize = this.getSize();
  43227. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  43228. // Base texture
  43229. newTexture.hasAlpha = this.hasAlpha;
  43230. newTexture.level = this.level;
  43231. // Mirror Texture
  43232. newTexture.mirrorPlane = this.mirrorPlane.clone();
  43233. newTexture.renderList = this.renderList.slice(0);
  43234. return newTexture;
  43235. };
  43236. MirrorTexture.prototype.serialize = function () {
  43237. if (!this.name) {
  43238. return null;
  43239. }
  43240. var serializationObject = _super.prototype.serialize.call(this);
  43241. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  43242. return serializationObject;
  43243. };
  43244. return MirrorTexture;
  43245. }(BABYLON.RenderTargetTexture));
  43246. BABYLON.MirrorTexture = MirrorTexture;
  43247. })(BABYLON || (BABYLON = {}));
  43248. //# sourceMappingURL=babylon.mirrorTexture.js.map
  43249. /// <reference path="babylon.renderTargetTexture.ts" />
  43250. var BABYLON;
  43251. (function (BABYLON) {
  43252. /**
  43253. * Creates a refraction texture used by refraction channel of the standard material.
  43254. * @param name the texture name
  43255. * @param size size of the underlying texture
  43256. * @param scene root scene
  43257. */
  43258. var RefractionTexture = (function (_super) {
  43259. __extends(RefractionTexture, _super);
  43260. function RefractionTexture(name, size, scene, generateMipMaps) {
  43261. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  43262. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  43263. _this.depth = 2.0;
  43264. _this.onBeforeRenderObservable.add(function () {
  43265. scene.clipPlane = _this.refractionPlane;
  43266. });
  43267. _this.onAfterRenderObservable.add(function () {
  43268. delete scene.clipPlane;
  43269. });
  43270. return _this;
  43271. }
  43272. RefractionTexture.prototype.clone = function () {
  43273. var textureSize = this.getSize();
  43274. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  43275. // Base texture
  43276. newTexture.hasAlpha = this.hasAlpha;
  43277. newTexture.level = this.level;
  43278. // Refraction Texture
  43279. newTexture.refractionPlane = this.refractionPlane.clone();
  43280. newTexture.renderList = this.renderList.slice(0);
  43281. newTexture.depth = this.depth;
  43282. return newTexture;
  43283. };
  43284. RefractionTexture.prototype.serialize = function () {
  43285. if (!this.name) {
  43286. return null;
  43287. }
  43288. var serializationObject = _super.prototype.serialize.call(this);
  43289. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  43290. serializationObject.depth = this.depth;
  43291. return serializationObject;
  43292. };
  43293. return RefractionTexture;
  43294. }(BABYLON.RenderTargetTexture));
  43295. BABYLON.RefractionTexture = RefractionTexture;
  43296. })(BABYLON || (BABYLON = {}));
  43297. //# sourceMappingURL=babylon.refractionTexture.js.map
  43298. /// <reference path="babylon.texture.ts" />
  43299. var BABYLON;
  43300. (function (BABYLON) {
  43301. var DynamicTexture = (function (_super) {
  43302. __extends(DynamicTexture, _super);
  43303. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  43304. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43305. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  43306. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  43307. _this.name = name;
  43308. var engine = _this.getScene().getEngine();
  43309. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43310. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43311. _this._generateMipMaps = generateMipMaps;
  43312. if (options.getContext) {
  43313. _this._canvas = options;
  43314. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  43315. }
  43316. else {
  43317. _this._canvas = document.createElement("canvas");
  43318. if (options.width) {
  43319. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  43320. }
  43321. else {
  43322. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  43323. }
  43324. }
  43325. var textureSize = _this.getSize();
  43326. _this._canvas.width = textureSize.width;
  43327. _this._canvas.height = textureSize.height;
  43328. _this._context = _this._canvas.getContext("2d");
  43329. return _this;
  43330. }
  43331. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  43332. get: function () {
  43333. return true;
  43334. },
  43335. enumerable: true,
  43336. configurable: true
  43337. });
  43338. DynamicTexture.prototype._recreate = function (textureSize) {
  43339. this._canvas.width = textureSize.width;
  43340. this._canvas.height = textureSize.height;
  43341. this.releaseInternalTexture();
  43342. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  43343. };
  43344. DynamicTexture.prototype.scale = function (ratio) {
  43345. var textureSize = this.getSize();
  43346. textureSize.width *= ratio;
  43347. textureSize.height *= ratio;
  43348. this._recreate(textureSize);
  43349. };
  43350. DynamicTexture.prototype.scaleTo = function (width, height) {
  43351. var textureSize = this.getSize();
  43352. textureSize.width = width;
  43353. textureSize.height = height;
  43354. this._recreate(textureSize);
  43355. };
  43356. DynamicTexture.prototype.getContext = function () {
  43357. return this._context;
  43358. };
  43359. DynamicTexture.prototype.clear = function () {
  43360. var size = this.getSize();
  43361. this._context.fillRect(0, 0, size.width, size.height);
  43362. };
  43363. DynamicTexture.prototype.update = function (invertY) {
  43364. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  43365. };
  43366. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  43367. if (update === void 0) { update = true; }
  43368. var size = this.getSize();
  43369. if (clearColor) {
  43370. this._context.fillStyle = clearColor;
  43371. this._context.fillRect(0, 0, size.width, size.height);
  43372. }
  43373. this._context.font = font;
  43374. if (x === null || x === undefined) {
  43375. var textSize = this._context.measureText(text);
  43376. x = (size.width - textSize.width) / 2;
  43377. }
  43378. if (y === null || y === undefined) {
  43379. var fontSize = parseInt((font.replace(/\D/g, '')));
  43380. ;
  43381. y = (size.height / 2) + (fontSize / 3.65);
  43382. }
  43383. this._context.fillStyle = color;
  43384. this._context.fillText(text, x, y);
  43385. if (update) {
  43386. this.update(invertY);
  43387. }
  43388. };
  43389. DynamicTexture.prototype.clone = function () {
  43390. var textureSize = this.getSize();
  43391. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  43392. // Base texture
  43393. newTexture.hasAlpha = this.hasAlpha;
  43394. newTexture.level = this.level;
  43395. // Dynamic Texture
  43396. newTexture.wrapU = this.wrapU;
  43397. newTexture.wrapV = this.wrapV;
  43398. return newTexture;
  43399. };
  43400. return DynamicTexture;
  43401. }(BABYLON.Texture));
  43402. BABYLON.DynamicTexture = DynamicTexture;
  43403. })(BABYLON || (BABYLON = {}));
  43404. //# sourceMappingURL=babylon.dynamicTexture.js.map
  43405. var BABYLON;
  43406. (function (BABYLON) {
  43407. var VideoTexture = (function (_super) {
  43408. __extends(VideoTexture, _super);
  43409. /**
  43410. * Creates a video texture.
  43411. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  43412. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  43413. * @param {BABYLON.Scene} scene is obviously the current scene.
  43414. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  43415. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  43416. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  43417. */
  43418. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  43419. if (generateMipMaps === void 0) { generateMipMaps = false; }
  43420. if (invertY === void 0) { invertY = false; }
  43421. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43422. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  43423. _this._autoLaunch = true;
  43424. var urls;
  43425. _this.name = name;
  43426. if (urlsOrVideo instanceof HTMLVideoElement) {
  43427. _this.video = urlsOrVideo;
  43428. }
  43429. else {
  43430. urls = urlsOrVideo;
  43431. _this.video = document.createElement("video");
  43432. _this.video.autoplay = false;
  43433. _this.video.loop = true;
  43434. }
  43435. _this._generateMipMaps = generateMipMaps;
  43436. _this._samplingMode = samplingMode;
  43437. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  43438. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  43439. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  43440. }
  43441. else {
  43442. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43443. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43444. _this._generateMipMaps = false;
  43445. }
  43446. if (urls) {
  43447. _this.video.addEventListener("canplay", function () {
  43448. _this._createTexture();
  43449. });
  43450. urls.forEach(function (url) {
  43451. var source = document.createElement("source");
  43452. source.src = url;
  43453. _this.video.appendChild(source);
  43454. });
  43455. }
  43456. else {
  43457. _this._createTexture();
  43458. }
  43459. _this._lastUpdate = BABYLON.Tools.Now;
  43460. return _this;
  43461. }
  43462. VideoTexture.prototype.__setTextureReady = function () {
  43463. this._texture.isReady = true;
  43464. };
  43465. VideoTexture.prototype._createTexture = function () {
  43466. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  43467. if (this._autoLaunch) {
  43468. this._autoLaunch = false;
  43469. this.video.play();
  43470. }
  43471. this._setTextureReady = this.__setTextureReady.bind(this);
  43472. this.video.addEventListener("playing", this._setTextureReady);
  43473. };
  43474. VideoTexture.prototype.update = function () {
  43475. var now = BABYLON.Tools.Now;
  43476. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  43477. return false;
  43478. }
  43479. this._lastUpdate = now;
  43480. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  43481. return true;
  43482. };
  43483. VideoTexture.prototype.dispose = function () {
  43484. _super.prototype.dispose.call(this);
  43485. this.video.removeEventListener("playing", this._setTextureReady);
  43486. };
  43487. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  43488. var video = document.createElement("video");
  43489. var constraintsDeviceId;
  43490. if (constraints && constraints.deviceId) {
  43491. constraintsDeviceId = {
  43492. exact: constraints.deviceId
  43493. };
  43494. }
  43495. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  43496. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  43497. if (navigator.getUserMedia) {
  43498. navigator.getUserMedia({
  43499. video: {
  43500. deviceId: constraintsDeviceId,
  43501. width: {
  43502. min: (constraints && constraints.minWidth) || 256,
  43503. max: (constraints && constraints.maxWidth) || 640
  43504. },
  43505. height: {
  43506. min: (constraints && constraints.minHeight) || 256,
  43507. max: (constraints && constraints.maxHeight) || 480
  43508. }
  43509. }
  43510. }, function (stream) {
  43511. if (video.mozSrcObject !== undefined) {
  43512. video.mozSrcObject = stream;
  43513. }
  43514. else {
  43515. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  43516. }
  43517. video.play();
  43518. if (onReady) {
  43519. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  43520. }
  43521. }, function (e) {
  43522. BABYLON.Tools.Error(e.name);
  43523. });
  43524. }
  43525. };
  43526. return VideoTexture;
  43527. }(BABYLON.Texture));
  43528. BABYLON.VideoTexture = VideoTexture;
  43529. })(BABYLON || (BABYLON = {}));
  43530. //# sourceMappingURL=babylon.videoTexture.js.map
  43531. var BABYLON;
  43532. (function (BABYLON) {
  43533. var RawTexture = (function (_super) {
  43534. __extends(RawTexture, _super);
  43535. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  43536. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43537. if (invertY === void 0) { invertY = false; }
  43538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43539. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  43540. _this.format = format;
  43541. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  43542. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43543. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43544. return _this;
  43545. }
  43546. RawTexture.prototype.update = function (data) {
  43547. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  43548. };
  43549. // Statics
  43550. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43551. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43552. if (invertY === void 0) { invertY = false; }
  43553. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43554. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  43555. };
  43556. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43557. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43558. if (invertY === void 0) { invertY = false; }
  43559. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43560. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43561. };
  43562. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43563. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43564. if (invertY === void 0) { invertY = false; }
  43565. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43566. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43567. };
  43568. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43569. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43570. if (invertY === void 0) { invertY = false; }
  43571. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43572. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  43573. };
  43574. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43575. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43576. if (invertY === void 0) { invertY = false; }
  43577. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43578. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  43579. };
  43580. return RawTexture;
  43581. }(BABYLON.Texture));
  43582. BABYLON.RawTexture = RawTexture;
  43583. })(BABYLON || (BABYLON = {}));
  43584. //# sourceMappingURL=babylon.rawTexture.js.map
  43585. var BABYLON;
  43586. (function (BABYLON) {
  43587. var PostProcess = (function () {
  43588. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  43589. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  43590. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43591. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  43592. if (blockCompilation === void 0) { blockCompilation = false; }
  43593. this.name = name;
  43594. this.width = -1;
  43595. this.height = -1;
  43596. this.autoClear = true;
  43597. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  43598. /*
  43599. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  43600. Can only be used on a single postprocess or on the last one of a chain.
  43601. */
  43602. this.enablePixelPerfectMode = false;
  43603. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  43604. this.alwaysForcePOT = false;
  43605. this.samples = 1;
  43606. this._reusable = false;
  43607. this._textures = new BABYLON.SmartArray(2);
  43608. this._currentRenderTextureInd = 0;
  43609. this._scaleRatio = new BABYLON.Vector2(1, 1);
  43610. this._texelSize = BABYLON.Vector2.Zero();
  43611. // Events
  43612. /**
  43613. * An event triggered when the postprocess is activated.
  43614. * @type {BABYLON.Observable}
  43615. */
  43616. this.onActivateObservable = new BABYLON.Observable();
  43617. /**
  43618. * An event triggered when the postprocess changes its size.
  43619. * @type {BABYLON.Observable}
  43620. */
  43621. this.onSizeChangedObservable = new BABYLON.Observable();
  43622. /**
  43623. * An event triggered when the postprocess applies its effect.
  43624. * @type {BABYLON.Observable}
  43625. */
  43626. this.onApplyObservable = new BABYLON.Observable();
  43627. /**
  43628. * An event triggered before rendering the postprocess
  43629. * @type {BABYLON.Observable}
  43630. */
  43631. this.onBeforeRenderObservable = new BABYLON.Observable();
  43632. /**
  43633. * An event triggered after rendering the postprocess
  43634. * @type {BABYLON.Observable}
  43635. */
  43636. this.onAfterRenderObservable = new BABYLON.Observable();
  43637. if (camera != null) {
  43638. this._camera = camera;
  43639. this._scene = camera.getScene();
  43640. camera.attachPostProcess(this);
  43641. this._engine = this._scene.getEngine();
  43642. }
  43643. else {
  43644. this._engine = engine;
  43645. }
  43646. this._options = options;
  43647. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  43648. this._reusable = reusable || false;
  43649. this._textureType = textureType;
  43650. this._samplers = samplers || [];
  43651. this._samplers.push("textureSampler");
  43652. this._fragmentUrl = fragmentUrl;
  43653. this._vertexUrl = vertexUrl;
  43654. this._parameters = parameters || [];
  43655. this._parameters.push("scale");
  43656. this._indexParameters = indexParameters;
  43657. if (!blockCompilation) {
  43658. this.updateEffect(defines);
  43659. }
  43660. }
  43661. Object.defineProperty(PostProcess.prototype, "onActivate", {
  43662. set: function (callback) {
  43663. if (this._onActivateObserver) {
  43664. this.onActivateObservable.remove(this._onActivateObserver);
  43665. }
  43666. this._onActivateObserver = this.onActivateObservable.add(callback);
  43667. },
  43668. enumerable: true,
  43669. configurable: true
  43670. });
  43671. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  43672. set: function (callback) {
  43673. if (this._onSizeChangedObserver) {
  43674. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  43675. }
  43676. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  43677. },
  43678. enumerable: true,
  43679. configurable: true
  43680. });
  43681. Object.defineProperty(PostProcess.prototype, "onApply", {
  43682. set: function (callback) {
  43683. if (this._onApplyObserver) {
  43684. this.onApplyObservable.remove(this._onApplyObserver);
  43685. }
  43686. this._onApplyObserver = this.onApplyObservable.add(callback);
  43687. },
  43688. enumerable: true,
  43689. configurable: true
  43690. });
  43691. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  43692. set: function (callback) {
  43693. if (this._onBeforeRenderObserver) {
  43694. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  43695. }
  43696. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  43697. },
  43698. enumerable: true,
  43699. configurable: true
  43700. });
  43701. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  43702. set: function (callback) {
  43703. if (this._onAfterRenderObserver) {
  43704. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  43705. }
  43706. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  43707. },
  43708. enumerable: true,
  43709. configurable: true
  43710. });
  43711. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  43712. get: function () {
  43713. return this._textures.data[this._currentRenderTextureInd];
  43714. },
  43715. set: function (value) {
  43716. this._forcedOutputTexture = value;
  43717. },
  43718. enumerable: true,
  43719. configurable: true
  43720. });
  43721. PostProcess.prototype.getCamera = function () {
  43722. return this._camera;
  43723. };
  43724. Object.defineProperty(PostProcess.prototype, "texelSize", {
  43725. get: function () {
  43726. if (this._shareOutputWithPostProcess) {
  43727. return this._shareOutputWithPostProcess.texelSize;
  43728. }
  43729. if (this._forcedOutputTexture) {
  43730. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  43731. }
  43732. return this._texelSize;
  43733. },
  43734. enumerable: true,
  43735. configurable: true
  43736. });
  43737. PostProcess.prototype.getEngine = function () {
  43738. return this._engine;
  43739. };
  43740. PostProcess.prototype.shareOutputWith = function (postProcess) {
  43741. this._disposeTextures();
  43742. this._shareOutputWithPostProcess = postProcess;
  43743. return this;
  43744. };
  43745. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters) {
  43746. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, null, null, indexParameters || this._indexParameters);
  43747. };
  43748. PostProcess.prototype.isReusable = function () {
  43749. return this._reusable;
  43750. };
  43751. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  43752. PostProcess.prototype.markTextureDirty = function () {
  43753. this.width = -1;
  43754. };
  43755. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  43756. var _this = this;
  43757. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  43758. camera = camera || this._camera;
  43759. var scene = camera.getScene();
  43760. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  43761. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  43762. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  43763. var desiredWidth = this._options.width || requiredWidth;
  43764. var desiredHeight = this._options.height || requiredHeight;
  43765. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  43766. if (!this._options.width) {
  43767. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  43768. }
  43769. if (!this._options.height) {
  43770. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  43771. }
  43772. }
  43773. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  43774. if (this._textures.length > 0) {
  43775. for (var i = 0; i < this._textures.length; i++) {
  43776. this._engine._releaseTexture(this._textures.data[i]);
  43777. }
  43778. this._textures.reset();
  43779. }
  43780. this.width = desiredWidth;
  43781. this.height = desiredHeight;
  43782. var textureSize = { width: this.width, height: this.height };
  43783. var textureOptions = {
  43784. generateMipMaps: false,
  43785. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  43786. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  43787. samplingMode: this.renderTargetSamplingMode,
  43788. type: this._textureType
  43789. };
  43790. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  43791. if (this._reusable) {
  43792. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  43793. }
  43794. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  43795. this.onSizeChangedObservable.notifyObservers(this);
  43796. }
  43797. this._textures.forEach(function (texture) {
  43798. if (texture.samples !== _this.samples) {
  43799. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  43800. }
  43801. });
  43802. }
  43803. var target;
  43804. if (this._shareOutputWithPostProcess) {
  43805. target = this._shareOutputWithPostProcess.outputTexture;
  43806. }
  43807. else if (this._forcedOutputTexture) {
  43808. target = this._forcedOutputTexture;
  43809. this.width = this._forcedOutputTexture._width;
  43810. this.height = this._forcedOutputTexture._height;
  43811. }
  43812. else {
  43813. target = this.outputTexture;
  43814. }
  43815. if (this.enablePixelPerfectMode) {
  43816. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  43817. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  43818. }
  43819. else {
  43820. this._scaleRatio.copyFromFloats(1, 1);
  43821. this._engine.bindFramebuffer(target);
  43822. }
  43823. this.onActivateObservable.notifyObservers(camera);
  43824. // Clear
  43825. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  43826. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  43827. }
  43828. if (this._reusable) {
  43829. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  43830. }
  43831. };
  43832. Object.defineProperty(PostProcess.prototype, "isSupported", {
  43833. get: function () {
  43834. return this._effect.isSupported;
  43835. },
  43836. enumerable: true,
  43837. configurable: true
  43838. });
  43839. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  43840. get: function () {
  43841. if (this._shareOutputWithPostProcess) {
  43842. return this._shareOutputWithPostProcess.aspectRatio;
  43843. }
  43844. if (this._forcedOutputTexture) {
  43845. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  43846. }
  43847. return this.width / this.height;
  43848. },
  43849. enumerable: true,
  43850. configurable: true
  43851. });
  43852. PostProcess.prototype.apply = function () {
  43853. // Check
  43854. if (!this._effect || !this._effect.isReady())
  43855. return null;
  43856. // States
  43857. this._engine.enableEffect(this._effect);
  43858. this._engine.setState(false);
  43859. this._engine.setDepthBuffer(false);
  43860. this._engine.setDepthWrite(false);
  43861. // Alpha
  43862. this._engine.setAlphaMode(this.alphaMode);
  43863. if (this.alphaConstants) {
  43864. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  43865. }
  43866. // Texture
  43867. var source;
  43868. if (this._shareOutputWithPostProcess) {
  43869. source = this._shareOutputWithPostProcess.outputTexture;
  43870. }
  43871. else if (this._forcedOutputTexture) {
  43872. source = this._forcedOutputTexture;
  43873. }
  43874. else {
  43875. source = this.outputTexture;
  43876. }
  43877. this._effect._bindTexture("textureSampler", source);
  43878. // Parameters
  43879. this._effect.setVector2("scale", this._scaleRatio);
  43880. this.onApplyObservable.notifyObservers(this._effect);
  43881. return this._effect;
  43882. };
  43883. PostProcess.prototype._disposeTextures = function () {
  43884. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  43885. return;
  43886. }
  43887. if (this._textures.length > 0) {
  43888. for (var i = 0; i < this._textures.length; i++) {
  43889. this._engine._releaseTexture(this._textures.data[i]);
  43890. }
  43891. }
  43892. this._textures.dispose();
  43893. };
  43894. PostProcess.prototype.dispose = function (camera) {
  43895. camera = camera || this._camera;
  43896. this._disposeTextures();
  43897. if (!camera) {
  43898. return;
  43899. }
  43900. camera.detachPostProcess(this);
  43901. var index = camera._postProcesses.indexOf(this);
  43902. if (index === 0 && camera._postProcesses.length > 0) {
  43903. this._camera._postProcesses[0].markTextureDirty();
  43904. }
  43905. this.onActivateObservable.clear();
  43906. this.onAfterRenderObservable.clear();
  43907. this.onApplyObservable.clear();
  43908. this.onBeforeRenderObservable.clear();
  43909. this.onSizeChangedObservable.clear();
  43910. };
  43911. return PostProcess;
  43912. }());
  43913. BABYLON.PostProcess = PostProcess;
  43914. })(BABYLON || (BABYLON = {}));
  43915. //# sourceMappingURL=babylon.postProcess.js.map
  43916. var BABYLON;
  43917. (function (BABYLON) {
  43918. var PassPostProcess = (function (_super) {
  43919. __extends(PassPostProcess, _super);
  43920. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  43921. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43922. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  43923. }
  43924. return PassPostProcess;
  43925. }(BABYLON.PostProcess));
  43926. BABYLON.PassPostProcess = PassPostProcess;
  43927. })(BABYLON || (BABYLON = {}));
  43928. //# sourceMappingURL=babylon.passPostProcess.js.map
  43929. var BABYLON;
  43930. (function (BABYLON) {
  43931. var ShadowGenerator = (function () {
  43932. /**
  43933. * Creates a ShadowGenerator object.
  43934. * A ShadowGenerator is the required tool to use the shadows.
  43935. * Each light casting shadows needs to use its own ShadowGenerator.
  43936. * Required parameters :
  43937. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  43938. * - `light` : the light object generating the shadows.
  43939. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  43940. */
  43941. function ShadowGenerator(mapSize, light) {
  43942. // Members
  43943. this._filter = ShadowGenerator.FILTER_NONE;
  43944. this.blurScale = 2;
  43945. this._blurBoxOffset = 0;
  43946. this._bias = 0.00005;
  43947. this._lightDirection = BABYLON.Vector3.Zero();
  43948. this.forceBackFacesOnly = false;
  43949. this._darkness = 0;
  43950. this._transparencyShadow = false;
  43951. this._viewMatrix = BABYLON.Matrix.Zero();
  43952. this._projectionMatrix = BABYLON.Matrix.Zero();
  43953. this._transformMatrix = BABYLON.Matrix.Zero();
  43954. this._worldViewProjection = BABYLON.Matrix.Zero();
  43955. this._currentFaceIndex = 0;
  43956. this._currentFaceIndexCache = 0;
  43957. this._isCube = false;
  43958. this._mapSize = mapSize;
  43959. this._light = light;
  43960. this._scene = light.getScene();
  43961. light._shadowGenerator = this;
  43962. // Texture type fallback from float to int if not supported.
  43963. var caps = this._scene.getEngine().getCaps();
  43964. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  43965. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43966. }
  43967. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  43968. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  43969. }
  43970. else {
  43971. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43972. }
  43973. this._initializeGenerator(1);
  43974. }
  43975. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  43976. // Static
  43977. get: function () {
  43978. return ShadowGenerator._FILTER_NONE;
  43979. },
  43980. enumerable: true,
  43981. configurable: true
  43982. });
  43983. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  43984. get: function () {
  43985. return ShadowGenerator._FILTER_POISSONSAMPLING;
  43986. },
  43987. enumerable: true,
  43988. configurable: true
  43989. });
  43990. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  43991. get: function () {
  43992. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  43993. },
  43994. enumerable: true,
  43995. configurable: true
  43996. });
  43997. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  43998. get: function () {
  43999. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  44000. },
  44001. enumerable: true,
  44002. configurable: true
  44003. });
  44004. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  44005. get: function () {
  44006. return this._bias;
  44007. },
  44008. set: function (bias) {
  44009. this._bias = bias;
  44010. },
  44011. enumerable: true,
  44012. configurable: true
  44013. });
  44014. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  44015. get: function () {
  44016. return this._blurBoxOffset;
  44017. },
  44018. set: function (value) {
  44019. var _this = this;
  44020. if (this._blurBoxOffset === value) {
  44021. return;
  44022. }
  44023. this._blurBoxOffset = value;
  44024. if (this._boxBlurPostprocess) {
  44025. this._boxBlurPostprocess.dispose();
  44026. }
  44027. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value, this._textureType);
  44028. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  44029. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  44030. });
  44031. },
  44032. enumerable: true,
  44033. configurable: true
  44034. });
  44035. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  44036. get: function () {
  44037. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  44038. },
  44039. set: function (value) {
  44040. this._depthScale = value;
  44041. },
  44042. enumerable: true,
  44043. configurable: true
  44044. });
  44045. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  44046. get: function () {
  44047. return this._filter;
  44048. },
  44049. set: function (value) {
  44050. if (this._filter === value) {
  44051. return;
  44052. }
  44053. this._filter = value;
  44054. this._applyFilterValues();
  44055. this._light._markMeshesAsLightDirty();
  44056. },
  44057. enumerable: true,
  44058. configurable: true
  44059. });
  44060. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  44061. get: function () {
  44062. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  44063. return this.useExponentialShadowMap;
  44064. },
  44065. set: function (value) {
  44066. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  44067. this.useExponentialShadowMap = value;
  44068. },
  44069. enumerable: true,
  44070. configurable: true
  44071. });
  44072. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  44073. get: function () {
  44074. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  44075. },
  44076. set: function (value) {
  44077. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44078. },
  44079. enumerable: true,
  44080. configurable: true
  44081. });
  44082. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  44083. get: function () {
  44084. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  44085. },
  44086. set: function (value) {
  44087. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  44088. },
  44089. enumerable: true,
  44090. configurable: true
  44091. });
  44092. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  44093. get: function () {
  44094. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  44095. return this.useBlurExponentialShadowMap;
  44096. },
  44097. set: function (value) {
  44098. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  44099. this.useBlurExponentialShadowMap = value;
  44100. },
  44101. enumerable: true,
  44102. configurable: true
  44103. });
  44104. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  44105. get: function () {
  44106. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  44107. },
  44108. set: function (value) {
  44109. if (this._light.needCube() && value) {
  44110. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  44111. }
  44112. else {
  44113. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44114. }
  44115. },
  44116. enumerable: true,
  44117. configurable: true
  44118. });
  44119. ShadowGenerator.prototype._initializeGenerator = function (boxBlurOffset) {
  44120. var _this = this;
  44121. var light = this._light;
  44122. var scene = this._scene;
  44123. var textureType = this._textureType;
  44124. light._markMeshesAsLightDirty();
  44125. // Render target
  44126. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", this._mapSize, this._scene, false, true, textureType, light.needCube());
  44127. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44128. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44129. this._shadowMap.anisotropicFilteringLevel = 1;
  44130. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44131. this._shadowMap.renderParticles = false;
  44132. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  44133. _this._currentFaceIndex = faceIndex;
  44134. });
  44135. this._shadowMap.onAfterUnbindObservable.add(function () {
  44136. if (!_this.useBlurExponentialShadowMap) {
  44137. return;
  44138. }
  44139. if (!_this._shadowMap2) {
  44140. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", _this._mapSize, _this._scene, false, true, textureType);
  44141. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44142. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44143. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44144. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  44145. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  44146. effect.setTexture("textureSampler", _this._shadowMap);
  44147. });
  44148. _this.blurBoxOffset = boxBlurOffset;
  44149. }
  44150. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  44151. });
  44152. // Custom render function
  44153. var renderSubMesh = function (subMesh) {
  44154. var mesh = subMesh.getRenderingMesh();
  44155. var scene = _this._scene;
  44156. var engine = scene.getEngine();
  44157. // Culling
  44158. engine.setState(subMesh.getMaterial().backFaceCulling);
  44159. // Managing instances
  44160. var batch = mesh._getInstancesRenderList(subMesh._id);
  44161. if (batch.mustReturn) {
  44162. return;
  44163. }
  44164. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44165. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  44166. engine.enableEffect(_this._effect);
  44167. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  44168. var material = subMesh.getMaterial();
  44169. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  44170. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  44171. _this._effect.setVector3("lightPosition", _this.getLight().position);
  44172. if (_this.getLight().needCube()) {
  44173. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  44174. }
  44175. // Alpha test
  44176. if (material && material.needAlphaTesting()) {
  44177. var alphaTexture = material.getAlphaTestTexture();
  44178. _this._effect.setTexture("diffuseSampler", alphaTexture);
  44179. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44180. }
  44181. // Bones
  44182. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44183. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44184. }
  44185. if (_this.forceBackFacesOnly) {
  44186. engine.setState(true, 0, false, true);
  44187. }
  44188. // Draw
  44189. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  44190. if (_this.forceBackFacesOnly) {
  44191. engine.setState(true, 0, false, false);
  44192. }
  44193. }
  44194. else {
  44195. // Need to reset refresh rate of the shadowMap
  44196. _this._shadowMap.resetRefreshCounter();
  44197. }
  44198. };
  44199. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  44200. var index;
  44201. for (index = 0; index < opaqueSubMeshes.length; index++) {
  44202. renderSubMesh(opaqueSubMeshes.data[index]);
  44203. }
  44204. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  44205. renderSubMesh(alphaTestSubMeshes.data[index]);
  44206. }
  44207. if (_this._transparencyShadow) {
  44208. for (index = 0; index < transparentSubMeshes.length; index++) {
  44209. renderSubMesh(transparentSubMeshes.data[index]);
  44210. }
  44211. }
  44212. };
  44213. this._shadowMap.onClearObservable.add(function (engine) {
  44214. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  44215. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  44216. }
  44217. else {
  44218. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  44219. }
  44220. });
  44221. };
  44222. ShadowGenerator.prototype._applyFilterValues = function () {
  44223. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  44224. this._shadowMap.anisotropicFilteringLevel = 16;
  44225. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44226. }
  44227. else {
  44228. this._shadowMap.anisotropicFilteringLevel = 1;
  44229. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  44230. }
  44231. };
  44232. ShadowGenerator.prototype.recreateShadowMap = function () {
  44233. // Track render list.
  44234. var renderList = this._shadowMap.renderList;
  44235. // Clean up existing data.
  44236. this._disposeRTTandPostProcesses();
  44237. // Reinitializes.
  44238. this._initializeGenerator(this.blurBoxOffset);
  44239. // Reaffect the blur ESM to ensure a correct fallback if necessary.
  44240. if (this.useBlurExponentialShadowMap) {
  44241. this.useBlurExponentialShadowMap = true;
  44242. }
  44243. // Reaffect the filter.
  44244. this._applyFilterValues();
  44245. // Reaffect Render List.
  44246. this._shadowMap.renderList = renderList;
  44247. };
  44248. /**
  44249. * Boolean : true when the ShadowGenerator is finally computed.
  44250. */
  44251. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  44252. var defines = [];
  44253. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44254. defines.push("#define FLOAT");
  44255. }
  44256. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  44257. defines.push("#define ESM");
  44258. }
  44259. if (this.getLight().needCube()) {
  44260. defines.push("#define CUBEMAP");
  44261. }
  44262. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44263. var mesh = subMesh.getMesh();
  44264. var material = subMesh.getMaterial();
  44265. // Alpha test
  44266. if (material && material.needAlphaTesting()) {
  44267. defines.push("#define ALPHATEST");
  44268. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44269. attribs.push(BABYLON.VertexBuffer.UVKind);
  44270. defines.push("#define UV1");
  44271. }
  44272. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44273. var alphaTexture = material.getAlphaTestTexture();
  44274. if (alphaTexture.coordinatesIndex === 1) {
  44275. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44276. defines.push("#define UV2");
  44277. }
  44278. }
  44279. }
  44280. // Bones
  44281. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44282. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44283. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44284. if (mesh.numBoneInfluencers > 4) {
  44285. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44286. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44287. }
  44288. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44289. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44290. }
  44291. else {
  44292. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44293. }
  44294. // Instances
  44295. if (useInstances) {
  44296. defines.push("#define INSTANCES");
  44297. attribs.push("world0");
  44298. attribs.push("world1");
  44299. attribs.push("world2");
  44300. attribs.push("world3");
  44301. }
  44302. // Get correct effect
  44303. var join = defines.join("\n");
  44304. if (this._cachedDefines !== join) {
  44305. this._cachedDefines = join;
  44306. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  44307. }
  44308. return this._effect.isReady();
  44309. };
  44310. /**
  44311. * Returns a RenderTargetTexture object : the shadow map texture.
  44312. */
  44313. ShadowGenerator.prototype.getShadowMap = function () {
  44314. return this._shadowMap;
  44315. };
  44316. /**
  44317. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  44318. */
  44319. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  44320. if (this._shadowMap2) {
  44321. return this._shadowMap2;
  44322. }
  44323. return this._shadowMap;
  44324. };
  44325. /**
  44326. * Returns the associated light object.
  44327. */
  44328. ShadowGenerator.prototype.getLight = function () {
  44329. return this._light;
  44330. };
  44331. // Methods
  44332. /**
  44333. * Returns a Matrix object : the updated transformation matrix.
  44334. */
  44335. ShadowGenerator.prototype.getTransformMatrix = function () {
  44336. var scene = this._scene;
  44337. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  44338. return this._transformMatrix;
  44339. }
  44340. this._currentRenderID = scene.getRenderId();
  44341. this._currentFaceIndexCache = this._currentFaceIndex;
  44342. var lightPosition = this._light.position;
  44343. if (this._light.computeTransformedInformation()) {
  44344. lightPosition = this._light.transformedPosition;
  44345. }
  44346. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  44347. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  44348. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  44349. }
  44350. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  44351. this._cachedPosition = lightPosition.clone();
  44352. this._cachedDirection = this._lightDirection.clone();
  44353. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  44354. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  44355. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  44356. }
  44357. return this._transformMatrix;
  44358. };
  44359. /**
  44360. * Returns the darkness value (float).
  44361. */
  44362. ShadowGenerator.prototype.getDarkness = function () {
  44363. return this._darkness;
  44364. };
  44365. /**
  44366. * Sets the ShadowGenerator darkness value (float <= 1.0).
  44367. * Returns the ShadowGenerator.
  44368. */
  44369. ShadowGenerator.prototype.setDarkness = function (darkness) {
  44370. if (darkness >= 1.0)
  44371. this._darkness = 1.0;
  44372. else if (darkness <= 0.0)
  44373. this._darkness = 0.0;
  44374. else
  44375. this._darkness = darkness;
  44376. return this;
  44377. };
  44378. /**
  44379. * Sets the ability to have transparent shadow (boolean).
  44380. * Returns the ShadowGenerator.
  44381. */
  44382. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  44383. this._transparencyShadow = hasShadow;
  44384. return this;
  44385. };
  44386. ShadowGenerator.prototype._packHalf = function (depth) {
  44387. var scale = depth * 255.0;
  44388. var fract = scale - Math.floor(scale);
  44389. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  44390. };
  44391. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  44392. if (this._shadowMap) {
  44393. this._shadowMap.dispose();
  44394. this._shadowMap = null;
  44395. }
  44396. if (this._shadowMap2) {
  44397. this._shadowMap2.dispose();
  44398. this._shadowMap2 = null;
  44399. }
  44400. if (this._downSamplePostprocess) {
  44401. this._downSamplePostprocess.dispose();
  44402. this._downSamplePostprocess = null;
  44403. }
  44404. if (this._boxBlurPostprocess) {
  44405. this._boxBlurPostprocess.dispose();
  44406. this._boxBlurPostprocess = null;
  44407. }
  44408. };
  44409. /**
  44410. * Disposes the ShadowGenerator.
  44411. * Returns nothing.
  44412. */
  44413. ShadowGenerator.prototype.dispose = function () {
  44414. this._disposeRTTandPostProcesses();
  44415. this._light._shadowGenerator = null;
  44416. this._light._markMeshesAsLightDirty();
  44417. };
  44418. /**
  44419. * Serializes the ShadowGenerator and returns a serializationObject.
  44420. */
  44421. ShadowGenerator.prototype.serialize = function () {
  44422. var serializationObject = {};
  44423. var shadowMap = this.getShadowMap();
  44424. serializationObject.lightId = this._light.id;
  44425. serializationObject.mapSize = shadowMap.getRenderSize();
  44426. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  44427. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  44428. serializationObject.usePoissonSampling = this.usePoissonSampling;
  44429. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  44430. serializationObject.depthScale = this.depthScale;
  44431. serializationObject.darkness = this.getDarkness();
  44432. serializationObject.renderList = [];
  44433. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  44434. var mesh = shadowMap.renderList[meshIndex];
  44435. serializationObject.renderList.push(mesh.id);
  44436. }
  44437. return serializationObject;
  44438. };
  44439. /**
  44440. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  44441. */
  44442. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  44443. //casting to point light, as light is missing the position attr and typescript complains.
  44444. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  44445. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  44446. var shadowMap = shadowGenerator.getShadowMap();
  44447. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  44448. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  44449. meshes.forEach(function (mesh) {
  44450. shadowMap.renderList.push(mesh);
  44451. });
  44452. }
  44453. if (parsedShadowGenerator.usePoissonSampling) {
  44454. shadowGenerator.usePoissonSampling = true;
  44455. }
  44456. else if (parsedShadowGenerator.useExponentialShadowMap) {
  44457. shadowGenerator.useExponentialShadowMap = true;
  44458. }
  44459. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  44460. shadowGenerator.useBlurExponentialShadowMap = true;
  44461. }
  44462. else if (parsedShadowGenerator.useVarianceShadowMap) {
  44463. shadowGenerator.useExponentialShadowMap = true;
  44464. }
  44465. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  44466. shadowGenerator.useBlurExponentialShadowMap = true;
  44467. }
  44468. if (parsedShadowGenerator.depthScale) {
  44469. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  44470. }
  44471. if (parsedShadowGenerator.blurScale) {
  44472. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  44473. }
  44474. if (parsedShadowGenerator.blurBoxOffset) {
  44475. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  44476. }
  44477. if (parsedShadowGenerator.bias !== undefined) {
  44478. shadowGenerator.bias = parsedShadowGenerator.bias;
  44479. }
  44480. if (parsedShadowGenerator.darkness) {
  44481. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  44482. }
  44483. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  44484. return shadowGenerator;
  44485. };
  44486. /**
  44487. * This creates the defines related to the standard BJS materials.
  44488. */
  44489. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  44490. var scene = this._scene;
  44491. var light = this._light;
  44492. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  44493. return;
  44494. }
  44495. defines["SHADOW" + lightIndex] = true;
  44496. if (this.usePoissonSampling) {
  44497. defines["SHADOWPCF" + lightIndex] = true;
  44498. }
  44499. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  44500. defines["SHADOWESM" + lightIndex] = true;
  44501. }
  44502. if (light.needCube()) {
  44503. defines["SHADOWCUBE" + lightIndex] = true;
  44504. }
  44505. };
  44506. /**
  44507. * This binds shadow lights related to the standard BJS materials.
  44508. * It implies the unifroms available on the materials are the standard BJS ones.
  44509. */
  44510. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect, depthValuesAlreadySet) {
  44511. var light = this._light;
  44512. var scene = this._scene;
  44513. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  44514. return;
  44515. }
  44516. if (!light.needCube()) {
  44517. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  44518. }
  44519. else {
  44520. if (!depthValuesAlreadySet) {
  44521. depthValuesAlreadySet = true;
  44522. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  44523. }
  44524. }
  44525. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  44526. light._uniformBuffer.updateFloat3("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, lightIndex);
  44527. return depthValuesAlreadySet;
  44528. };
  44529. return ShadowGenerator;
  44530. }());
  44531. ShadowGenerator._FILTER_NONE = 0;
  44532. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  44533. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  44534. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  44535. BABYLON.ShadowGenerator = ShadowGenerator;
  44536. })(BABYLON || (BABYLON = {}));
  44537. //# sourceMappingURL=babylon.shadowGenerator.js.map
  44538. var BABYLON;
  44539. (function (BABYLON) {
  44540. var DefaultLoadingScreen = (function () {
  44541. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  44542. if (_loadingText === void 0) { _loadingText = ""; }
  44543. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  44544. var _this = this;
  44545. this._renderingCanvas = _renderingCanvas;
  44546. this._loadingText = _loadingText;
  44547. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  44548. // Resize
  44549. this._resizeLoadingUI = function () {
  44550. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  44551. _this._loadingDiv.style.position = "absolute";
  44552. _this._loadingDiv.style.left = canvasRect.left + "px";
  44553. _this._loadingDiv.style.top = canvasRect.top + "px";
  44554. _this._loadingDiv.style.width = canvasRect.width + "px";
  44555. _this._loadingDiv.style.height = canvasRect.height + "px";
  44556. };
  44557. }
  44558. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  44559. var _this = this;
  44560. if (this._loadingDiv) {
  44561. // Do not add a loading screen if there is already one
  44562. return;
  44563. }
  44564. this._loadingDiv = document.createElement("div");
  44565. this._loadingDiv.id = "babylonjsLoadingDiv";
  44566. this._loadingDiv.style.opacity = "0";
  44567. this._loadingDiv.style.transition = "opacity 1.5s ease";
  44568. // Loading text
  44569. this._loadingTextDiv = document.createElement("div");
  44570. this._loadingTextDiv.style.position = "absolute";
  44571. this._loadingTextDiv.style.left = "0";
  44572. this._loadingTextDiv.style.top = "50%";
  44573. this._loadingTextDiv.style.marginTop = "80px";
  44574. this._loadingTextDiv.style.width = "100%";
  44575. this._loadingTextDiv.style.height = "20px";
  44576. this._loadingTextDiv.style.fontFamily = "Arial";
  44577. this._loadingTextDiv.style.fontSize = "14px";
  44578. this._loadingTextDiv.style.color = "white";
  44579. this._loadingTextDiv.style.textAlign = "center";
  44580. this._loadingTextDiv.innerHTML = "Loading";
  44581. this._loadingDiv.appendChild(this._loadingTextDiv);
  44582. //set the predefined text
  44583. this._loadingTextDiv.innerHTML = this._loadingText;
  44584. // Loading img
  44585. var imgBack = new Image();
  44586. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  44587. imgBack.style.position = "absolute";
  44588. imgBack.style.left = "50%";
  44589. imgBack.style.top = "50%";
  44590. imgBack.style.marginLeft = "-50px";
  44591. imgBack.style.marginTop = "-50px";
  44592. imgBack.style.transition = "transform 1.0s ease";
  44593. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  44594. var deg = 360;
  44595. var onTransitionEnd = function () {
  44596. deg += 360;
  44597. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  44598. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  44599. };
  44600. imgBack.addEventListener("transitionend", onTransitionEnd);
  44601. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  44602. this._loadingDiv.appendChild(imgBack);
  44603. // front image
  44604. var imgFront = new Image();
  44605. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  44606. imgFront.style.position = "absolute";
  44607. imgFront.style.left = "50%";
  44608. imgFront.style.top = "50%";
  44609. imgFront.style.marginLeft = "-50px";
  44610. imgFront.style.marginTop = "-50px";
  44611. this._loadingDiv.appendChild(imgFront);
  44612. this._resizeLoadingUI();
  44613. window.addEventListener("resize", this._resizeLoadingUI);
  44614. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  44615. document.body.appendChild(this._loadingDiv);
  44616. setTimeout(function () {
  44617. _this._loadingDiv.style.opacity = "1";
  44618. imgBack.style.transform = "rotateZ(360deg)";
  44619. imgBack.style.webkitTransform = "rotateZ(360deg)";
  44620. }, 0);
  44621. };
  44622. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  44623. var _this = this;
  44624. if (!this._loadingDiv) {
  44625. return;
  44626. }
  44627. var onTransitionEnd = function () {
  44628. if (!_this._loadingDiv) {
  44629. return;
  44630. }
  44631. document.body.removeChild(_this._loadingDiv);
  44632. window.removeEventListener("resize", _this._resizeLoadingUI);
  44633. _this._loadingDiv = null;
  44634. };
  44635. this._loadingDiv.style.opacity = "0";
  44636. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  44637. };
  44638. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  44639. set: function (text) {
  44640. this._loadingText = text;
  44641. if (this._loadingTextDiv) {
  44642. this._loadingTextDiv.innerHTML = this._loadingText;
  44643. }
  44644. },
  44645. enumerable: true,
  44646. configurable: true
  44647. });
  44648. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  44649. get: function () {
  44650. return this._loadingDivBackgroundColor;
  44651. },
  44652. set: function (color) {
  44653. this._loadingDivBackgroundColor = color;
  44654. if (!this._loadingDiv) {
  44655. return;
  44656. }
  44657. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  44658. },
  44659. enumerable: true,
  44660. configurable: true
  44661. });
  44662. return DefaultLoadingScreen;
  44663. }());
  44664. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  44665. })(BABYLON || (BABYLON = {}));
  44666. //# sourceMappingURL=babylon.loadingScreen.js.map
  44667. var BABYLON;
  44668. (function (BABYLON) {
  44669. var SceneLoader = (function () {
  44670. function SceneLoader() {
  44671. }
  44672. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  44673. get: function () {
  44674. return 0;
  44675. },
  44676. enumerable: true,
  44677. configurable: true
  44678. });
  44679. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  44680. get: function () {
  44681. return 1;
  44682. },
  44683. enumerable: true,
  44684. configurable: true
  44685. });
  44686. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  44687. get: function () {
  44688. return 2;
  44689. },
  44690. enumerable: true,
  44691. configurable: true
  44692. });
  44693. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  44694. get: function () {
  44695. return 3;
  44696. },
  44697. enumerable: true,
  44698. configurable: true
  44699. });
  44700. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  44701. get: function () {
  44702. return SceneLoader._ForceFullSceneLoadingForIncremental;
  44703. },
  44704. set: function (value) {
  44705. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  44706. },
  44707. enumerable: true,
  44708. configurable: true
  44709. });
  44710. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  44711. get: function () {
  44712. return SceneLoader._ShowLoadingScreen;
  44713. },
  44714. set: function (value) {
  44715. SceneLoader._ShowLoadingScreen = value;
  44716. },
  44717. enumerable: true,
  44718. configurable: true
  44719. });
  44720. Object.defineProperty(SceneLoader, "loggingLevel", {
  44721. get: function () {
  44722. return SceneLoader._loggingLevel;
  44723. },
  44724. set: function (value) {
  44725. SceneLoader._loggingLevel = value;
  44726. },
  44727. enumerable: true,
  44728. configurable: true
  44729. });
  44730. SceneLoader._getDefaultPlugin = function () {
  44731. return SceneLoader._registeredPlugins[".babylon"];
  44732. };
  44733. SceneLoader._getPluginForExtension = function (extension) {
  44734. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  44735. if (registeredPlugin) {
  44736. return registeredPlugin;
  44737. }
  44738. return SceneLoader._getDefaultPlugin();
  44739. };
  44740. SceneLoader._getPluginForDirectLoad = function (data) {
  44741. for (var extension in SceneLoader._registeredPlugins) {
  44742. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  44743. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  44744. return SceneLoader._registeredPlugins[extension];
  44745. }
  44746. }
  44747. return SceneLoader._getDefaultPlugin();
  44748. };
  44749. SceneLoader._getPluginForFilename = function (sceneFilename) {
  44750. if (sceneFilename.name) {
  44751. sceneFilename = sceneFilename.name;
  44752. }
  44753. var dotPosition = sceneFilename.lastIndexOf(".");
  44754. var queryStringPosition = sceneFilename.indexOf("?");
  44755. if (queryStringPosition === -1) {
  44756. queryStringPosition = sceneFilename.length;
  44757. }
  44758. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  44759. return SceneLoader._getPluginForExtension(extension);
  44760. };
  44761. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  44762. SceneLoader._getDirectLoad = function (sceneFilename) {
  44763. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  44764. return sceneFilename.substr(5);
  44765. }
  44766. return null;
  44767. };
  44768. // Public functions
  44769. SceneLoader.GetPluginForExtension = function (extension) {
  44770. return SceneLoader._getPluginForExtension(extension).plugin;
  44771. };
  44772. SceneLoader.RegisterPlugin = function (plugin) {
  44773. if (typeof plugin.extensions === "string") {
  44774. var extension = plugin.extensions;
  44775. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  44776. plugin: plugin,
  44777. isBinary: false
  44778. };
  44779. }
  44780. else {
  44781. var extensions = plugin.extensions;
  44782. Object.keys(extensions).forEach(function (extension) {
  44783. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  44784. plugin: plugin,
  44785. isBinary: extensions[extension].isBinary
  44786. };
  44787. });
  44788. }
  44789. };
  44790. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  44791. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  44792. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  44793. return;
  44794. }
  44795. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  44796. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  44797. return;
  44798. }
  44799. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  44800. var loadingToken = {};
  44801. scene._addPendingData(loadingToken);
  44802. var manifestChecked = function (success) {
  44803. scene.database = database;
  44804. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(directLoad) : SceneLoader._getPluginForFilename(sceneFilename);
  44805. var plugin = registeredPlugin.plugin;
  44806. var useArrayBuffer = registeredPlugin.isBinary;
  44807. var importMeshFromData = function (data) {
  44808. var meshes = [];
  44809. var particleSystems = [];
  44810. var skeletons = [];
  44811. if (scene.isDisposed) {
  44812. if (onerror) {
  44813. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  44814. }
  44815. return;
  44816. }
  44817. try {
  44818. if (plugin.importMesh) {
  44819. var syncedPlugin = plugin;
  44820. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  44821. if (onerror) {
  44822. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  44823. }
  44824. scene._removePendingData(loadingToken);
  44825. return;
  44826. }
  44827. if (onsuccess) {
  44828. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  44829. onsuccess(meshes, particleSystems, skeletons);
  44830. scene._removePendingData(loadingToken);
  44831. }
  44832. }
  44833. else {
  44834. var asyncedPlugin = plugin;
  44835. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  44836. if (onsuccess) {
  44837. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  44838. onsuccess(meshes, particleSystems, skeletons);
  44839. scene._removePendingData(loadingToken);
  44840. }
  44841. }, function () {
  44842. if (onerror) {
  44843. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  44844. }
  44845. scene._removePendingData(loadingToken);
  44846. });
  44847. }
  44848. }
  44849. catch (e) {
  44850. if (onerror) {
  44851. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  44852. }
  44853. scene._removePendingData(loadingToken);
  44854. }
  44855. };
  44856. if (directLoad) {
  44857. importMeshFromData(directLoad);
  44858. return;
  44859. }
  44860. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  44861. importMeshFromData(data);
  44862. }, progressCallBack, database, useArrayBuffer, function () {
  44863. if (onerror) {
  44864. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  44865. }
  44866. });
  44867. };
  44868. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  44869. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  44870. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  44871. }
  44872. else {
  44873. // If the scene is a data stream or offline support is not enabled, it's a direct load
  44874. manifestChecked(true);
  44875. }
  44876. };
  44877. /**
  44878. * Load a scene
  44879. * @param rootUrl a string that defines the root url for scene and resources
  44880. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  44881. * @param engine is the instance of BABYLON.Engine to use to create the scene
  44882. */
  44883. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  44884. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  44885. };
  44886. /**
  44887. * Append a scene
  44888. * @param rootUrl a string that defines the root url for scene and resources
  44889. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  44890. * @param scene is the instance of BABYLON.Scene to append to
  44891. */
  44892. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  44893. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  44894. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  44895. return;
  44896. }
  44897. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  44898. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  44899. var plugin = registeredPlugin.plugin;
  44900. var useArrayBuffer = registeredPlugin.isBinary;
  44901. var database;
  44902. var loadingToken = {};
  44903. scene._addPendingData(loadingToken);
  44904. if (SceneLoader.ShowLoadingScreen) {
  44905. scene.getEngine().displayLoadingUI();
  44906. }
  44907. var loadSceneFromData = function (data) {
  44908. scene.database = database;
  44909. if (plugin.load) {
  44910. var syncedPlugin = plugin;
  44911. if (!syncedPlugin.load(scene, data, rootUrl)) {
  44912. if (onerror) {
  44913. onerror(scene);
  44914. }
  44915. scene._removePendingData(loadingToken);
  44916. scene.getEngine().hideLoadingUI();
  44917. return;
  44918. }
  44919. if (onsuccess) {
  44920. onsuccess(scene);
  44921. }
  44922. scene._removePendingData(loadingToken);
  44923. }
  44924. else {
  44925. var asyncedPlugin = plugin;
  44926. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  44927. if (onsuccess) {
  44928. onsuccess(scene);
  44929. }
  44930. scene._removePendingData(loadingToken);
  44931. }, function () {
  44932. if (onerror) {
  44933. onerror(scene);
  44934. }
  44935. scene._removePendingData(loadingToken);
  44936. scene.getEngine().hideLoadingUI();
  44937. });
  44938. }
  44939. if (SceneLoader.ShowLoadingScreen) {
  44940. scene.executeWhenReady(function () {
  44941. scene.getEngine().hideLoadingUI();
  44942. });
  44943. }
  44944. };
  44945. var manifestChecked = function (success) {
  44946. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  44947. };
  44948. if (directLoad) {
  44949. loadSceneFromData(directLoad);
  44950. return;
  44951. }
  44952. if (rootUrl.indexOf("file:") === -1) {
  44953. if (scene.getEngine().enableOfflineSupport) {
  44954. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  44955. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  44956. }
  44957. else {
  44958. manifestChecked(true);
  44959. }
  44960. }
  44961. else {
  44962. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  44963. }
  44964. };
  44965. return SceneLoader;
  44966. }());
  44967. // Flags
  44968. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  44969. SceneLoader._ShowLoadingScreen = true;
  44970. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  44971. // Members
  44972. SceneLoader._registeredPlugins = {};
  44973. BABYLON.SceneLoader = SceneLoader;
  44974. ;
  44975. })(BABYLON || (BABYLON = {}));
  44976. //# sourceMappingURL=babylon.sceneLoader.js.map
  44977. var BABYLON;
  44978. (function (BABYLON) {
  44979. var Internals;
  44980. (function (Internals) {
  44981. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  44982. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  44983. var parsedMaterial = parsedData.materials[index];
  44984. if (parsedMaterial.id === id) {
  44985. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  44986. }
  44987. }
  44988. return null;
  44989. };
  44990. var isDescendantOf = function (mesh, names, hierarchyIds) {
  44991. names = (names instanceof Array) ? names : [names];
  44992. for (var i in names) {
  44993. if (mesh.name === names[i]) {
  44994. hierarchyIds.push(mesh.id);
  44995. return true;
  44996. }
  44997. }
  44998. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  44999. hierarchyIds.push(mesh.id);
  45000. return true;
  45001. }
  45002. return false;
  45003. };
  45004. var logOperation = function (operation, producer) {
  45005. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  45006. };
  45007. BABYLON.SceneLoader.RegisterPlugin({
  45008. extensions: ".babylon",
  45009. canDirectLoad: function (data) {
  45010. if (data.indexOf("babylon") !== -1) {
  45011. return true;
  45012. }
  45013. return false;
  45014. },
  45015. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  45016. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  45017. // when SceneLoader.debugLogging = true (default), or exception encountered.
  45018. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  45019. // and avoid problems with multiple concurrent .babylon loads.
  45020. var log = "importMesh has failed JSON parse";
  45021. try {
  45022. var parsedData = JSON.parse(data);
  45023. log = "";
  45024. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  45025. var loadedSkeletonsIds = [];
  45026. var loadedMaterialsIds = [];
  45027. var hierarchyIds = [];
  45028. var index;
  45029. var cache;
  45030. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  45031. var parsedMesh = parsedData.meshes[index];
  45032. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  45033. if (meshesNames instanceof Array) {
  45034. // Remove found mesh name from list.
  45035. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  45036. }
  45037. //Geometry?
  45038. if (parsedMesh.geometryId) {
  45039. //does the file contain geometries?
  45040. if (parsedData.geometries) {
  45041. //find the correct geometry and add it to the scene
  45042. var found = false;
  45043. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  45044. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  45045. return;
  45046. }
  45047. else {
  45048. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  45049. if (parsedGeometryData.id === parsedMesh.geometryId) {
  45050. switch (geometryType) {
  45051. case "boxes":
  45052. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  45053. break;
  45054. case "spheres":
  45055. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  45056. break;
  45057. case "cylinders":
  45058. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  45059. break;
  45060. case "toruses":
  45061. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  45062. break;
  45063. case "grounds":
  45064. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  45065. break;
  45066. case "planes":
  45067. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  45068. break;
  45069. case "torusKnots":
  45070. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  45071. break;
  45072. case "vertexData":
  45073. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  45074. break;
  45075. }
  45076. found = true;
  45077. }
  45078. });
  45079. }
  45080. });
  45081. if (!found) {
  45082. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  45083. }
  45084. }
  45085. }
  45086. // Material ?
  45087. if (parsedMesh.materialId) {
  45088. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  45089. if (!materialFound && parsedData.multiMaterials) {
  45090. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  45091. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  45092. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  45093. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  45094. var subMatId = parsedMultiMaterial.materials[matIndex];
  45095. loadedMaterialsIds.push(subMatId);
  45096. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  45097. log += "\n\tMaterial " + mat.toString(fullDetails);
  45098. }
  45099. loadedMaterialsIds.push(parsedMultiMaterial.id);
  45100. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  45101. materialFound = true;
  45102. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  45103. break;
  45104. }
  45105. }
  45106. }
  45107. if (!materialFound) {
  45108. loadedMaterialsIds.push(parsedMesh.materialId);
  45109. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  45110. if (!mat) {
  45111. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  45112. }
  45113. else {
  45114. log += "\n\tMaterial " + mat.toString(fullDetails);
  45115. }
  45116. }
  45117. }
  45118. // Skeleton ?
  45119. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  45120. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  45121. if (!skeletonAlreadyLoaded) {
  45122. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  45123. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  45124. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  45125. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  45126. skeletons.push(skeleton);
  45127. loadedSkeletonsIds.push(parsedSkeleton.id);
  45128. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  45129. }
  45130. }
  45131. }
  45132. }
  45133. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  45134. meshes.push(mesh);
  45135. log += "\n\tMesh " + mesh.toString(fullDetails);
  45136. }
  45137. }
  45138. // Connecting parents
  45139. var currentMesh;
  45140. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45141. currentMesh = scene.meshes[index];
  45142. if (currentMesh._waitingParentId) {
  45143. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  45144. currentMesh._waitingParentId = undefined;
  45145. }
  45146. }
  45147. // freeze and compute world matrix application
  45148. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45149. currentMesh = scene.meshes[index];
  45150. if (currentMesh._waitingFreezeWorldMatrix) {
  45151. currentMesh.freezeWorldMatrix();
  45152. currentMesh._waitingFreezeWorldMatrix = undefined;
  45153. }
  45154. else {
  45155. currentMesh.computeWorldMatrix(true);
  45156. }
  45157. }
  45158. // Particles
  45159. if (parsedData.particleSystems) {
  45160. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  45161. var parsedParticleSystem = parsedData.particleSystems[index];
  45162. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  45163. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  45164. }
  45165. }
  45166. }
  45167. return true;
  45168. }
  45169. catch (err) {
  45170. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  45171. log = null;
  45172. throw err;
  45173. }
  45174. finally {
  45175. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  45176. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  45177. }
  45178. }
  45179. },
  45180. load: function (scene, data, rootUrl) {
  45181. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  45182. // when SceneLoader.debugLogging = true (default), or exception encountered.
  45183. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  45184. // and avoid problems with multiple concurrent .babylon loads.
  45185. var log = "importScene has failed JSON parse";
  45186. try {
  45187. var parsedData = JSON.parse(data);
  45188. log = "";
  45189. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  45190. // Scene
  45191. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  45192. scene.autoClear = parsedData.autoClear;
  45193. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  45194. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  45195. if (parsedData.gravity) {
  45196. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  45197. }
  45198. // Fog
  45199. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  45200. scene.fogMode = parsedData.fogMode;
  45201. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  45202. scene.fogStart = parsedData.fogStart;
  45203. scene.fogEnd = parsedData.fogEnd;
  45204. scene.fogDensity = parsedData.fogDensity;
  45205. log += "\tFog mode for scene: ";
  45206. switch (scene.fogMode) {
  45207. // getters not compiling, so using hardcoded
  45208. case 1:
  45209. log += "exp\n";
  45210. break;
  45211. case 2:
  45212. log += "exp2\n";
  45213. break;
  45214. case 3:
  45215. log += "linear\n";
  45216. break;
  45217. }
  45218. }
  45219. //Physics
  45220. if (parsedData.physicsEnabled) {
  45221. var physicsPlugin;
  45222. if (parsedData.physicsEngine === "cannon") {
  45223. physicsPlugin = new BABYLON.CannonJSPlugin();
  45224. }
  45225. else if (parsedData.physicsEngine === "oimo") {
  45226. physicsPlugin = new BABYLON.OimoJSPlugin();
  45227. }
  45228. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  45229. //else - default engine, which is currently oimo
  45230. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  45231. scene.enablePhysics(physicsGravity, physicsPlugin);
  45232. }
  45233. // Metadata
  45234. if (parsedData.metadata !== undefined) {
  45235. scene.metadata = parsedData.metadata;
  45236. }
  45237. //collisions, if defined. otherwise, default is true
  45238. if (parsedData.collisionsEnabled != undefined) {
  45239. scene.collisionsEnabled = parsedData.collisionsEnabled;
  45240. }
  45241. scene.workerCollisions = !!parsedData.workerCollisions;
  45242. var index;
  45243. var cache;
  45244. // Lights
  45245. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  45246. var parsedLight = parsedData.lights[index];
  45247. var light = BABYLON.Light.Parse(parsedLight, scene);
  45248. log += (index === 0 ? "\n\tLights:" : "");
  45249. log += "\n\t\t" + light.toString(fullDetails);
  45250. }
  45251. // Animations
  45252. if (parsedData.animations) {
  45253. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  45254. var parsedAnimation = parsedData.animations[index];
  45255. var animation = BABYLON.Animation.Parse(parsedAnimation);
  45256. scene.animations.push(animation);
  45257. log += (index === 0 ? "\n\tAnimations:" : "");
  45258. log += "\n\t\t" + animation.toString(fullDetails);
  45259. }
  45260. }
  45261. if (parsedData.autoAnimate) {
  45262. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  45263. }
  45264. // Materials
  45265. if (parsedData.materials) {
  45266. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  45267. var parsedMaterial = parsedData.materials[index];
  45268. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  45269. log += (index === 0 ? "\n\tMaterials:" : "");
  45270. log += "\n\t\t" + mat.toString(fullDetails);
  45271. }
  45272. }
  45273. if (parsedData.multiMaterials) {
  45274. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  45275. var parsedMultiMaterial = parsedData.multiMaterials[index];
  45276. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  45277. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  45278. log += "\n\t\t" + mmat.toString(fullDetails);
  45279. }
  45280. }
  45281. // Morph targets
  45282. if (parsedData.morphTargetManagers) {
  45283. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  45284. var managerData = _a[_i];
  45285. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  45286. }
  45287. }
  45288. // Skeletons
  45289. if (parsedData.skeletons) {
  45290. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  45291. var parsedSkeleton = parsedData.skeletons[index];
  45292. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  45293. log += (index === 0 ? "\n\tSkeletons:" : "");
  45294. log += "\n\t\t" + skeleton.toString(fullDetails);
  45295. }
  45296. }
  45297. // Geometries
  45298. var geometries = parsedData.geometries;
  45299. if (geometries) {
  45300. // Boxes
  45301. var boxes = geometries.boxes;
  45302. if (boxes) {
  45303. for (index = 0, cache = boxes.length; index < cache; index++) {
  45304. var parsedBox = boxes[index];
  45305. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  45306. }
  45307. }
  45308. // Spheres
  45309. var spheres = geometries.spheres;
  45310. if (spheres) {
  45311. for (index = 0, cache = spheres.length; index < cache; index++) {
  45312. var parsedSphere = spheres[index];
  45313. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  45314. }
  45315. }
  45316. // Cylinders
  45317. var cylinders = geometries.cylinders;
  45318. if (cylinders) {
  45319. for (index = 0, cache = cylinders.length; index < cache; index++) {
  45320. var parsedCylinder = cylinders[index];
  45321. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  45322. }
  45323. }
  45324. // Toruses
  45325. var toruses = geometries.toruses;
  45326. if (toruses) {
  45327. for (index = 0, cache = toruses.length; index < cache; index++) {
  45328. var parsedTorus = toruses[index];
  45329. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  45330. }
  45331. }
  45332. // Grounds
  45333. var grounds = geometries.grounds;
  45334. if (grounds) {
  45335. for (index = 0, cache = grounds.length; index < cache; index++) {
  45336. var parsedGround = grounds[index];
  45337. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  45338. }
  45339. }
  45340. // Planes
  45341. var planes = geometries.planes;
  45342. if (planes) {
  45343. for (index = 0, cache = planes.length; index < cache; index++) {
  45344. var parsedPlane = planes[index];
  45345. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  45346. }
  45347. }
  45348. // TorusKnots
  45349. var torusKnots = geometries.torusKnots;
  45350. if (torusKnots) {
  45351. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  45352. var parsedTorusKnot = torusKnots[index];
  45353. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  45354. }
  45355. }
  45356. // VertexData
  45357. var vertexData = geometries.vertexData;
  45358. if (vertexData) {
  45359. for (index = 0, cache = vertexData.length; index < cache; index++) {
  45360. var parsedVertexData = vertexData[index];
  45361. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  45362. }
  45363. }
  45364. }
  45365. // Meshes
  45366. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  45367. var parsedMesh = parsedData.meshes[index];
  45368. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  45369. log += (index === 0 ? "\n\tMeshes:" : "");
  45370. log += "\n\t\t" + mesh.toString(fullDetails);
  45371. }
  45372. // Cameras
  45373. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  45374. var parsedCamera = parsedData.cameras[index];
  45375. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  45376. log += (index === 0 ? "\n\tCameras:" : "");
  45377. log += "\n\t\t" + camera.toString(fullDetails);
  45378. }
  45379. if (parsedData.activeCameraID) {
  45380. scene.setActiveCameraByID(parsedData.activeCameraID);
  45381. }
  45382. // Browsing all the graph to connect the dots
  45383. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  45384. var camera = scene.cameras[index];
  45385. if (camera._waitingParentId) {
  45386. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  45387. camera._waitingParentId = undefined;
  45388. }
  45389. }
  45390. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  45391. var light = scene.lights[index];
  45392. if (light._waitingParentId) {
  45393. light.parent = scene.getLastEntryByID(light._waitingParentId);
  45394. light._waitingParentId = undefined;
  45395. }
  45396. }
  45397. // Sounds
  45398. var loadedSounds = [];
  45399. var loadedSound;
  45400. if (BABYLON.AudioEngine && parsedData.sounds) {
  45401. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  45402. var parsedSound = parsedData.sounds[index];
  45403. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45404. if (!parsedSound.url)
  45405. parsedSound.url = parsedSound.name;
  45406. if (!loadedSounds[parsedSound.url]) {
  45407. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  45408. loadedSounds[parsedSound.url] = loadedSound;
  45409. }
  45410. else {
  45411. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  45412. }
  45413. }
  45414. else {
  45415. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  45416. }
  45417. }
  45418. }
  45419. loadedSounds = [];
  45420. // Connect parents & children and parse actions
  45421. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45422. var mesh = scene.meshes[index];
  45423. if (mesh._waitingParentId) {
  45424. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  45425. mesh._waitingParentId = undefined;
  45426. }
  45427. if (mesh._waitingActions) {
  45428. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  45429. mesh._waitingActions = undefined;
  45430. }
  45431. }
  45432. // freeze world matrix application
  45433. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45434. var currentMesh = scene.meshes[index];
  45435. if (currentMesh._waitingFreezeWorldMatrix) {
  45436. currentMesh.freezeWorldMatrix();
  45437. currentMesh._waitingFreezeWorldMatrix = undefined;
  45438. }
  45439. else {
  45440. currentMesh.computeWorldMatrix(true);
  45441. }
  45442. }
  45443. // Particles Systems
  45444. if (parsedData.particleSystems) {
  45445. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  45446. var parsedParticleSystem = parsedData.particleSystems[index];
  45447. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  45448. }
  45449. }
  45450. // Lens flares
  45451. if (parsedData.lensFlareSystems) {
  45452. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  45453. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  45454. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  45455. }
  45456. }
  45457. // Shadows
  45458. if (parsedData.shadowGenerators) {
  45459. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  45460. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  45461. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  45462. }
  45463. }
  45464. // Lights exclusions / inclusions
  45465. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  45466. var light = scene.lights[index];
  45467. // Excluded check
  45468. if (light._excludedMeshesIds.length > 0) {
  45469. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  45470. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  45471. if (excludedMesh) {
  45472. light.excludedMeshes.push(excludedMesh);
  45473. }
  45474. }
  45475. light._excludedMeshesIds = [];
  45476. }
  45477. // Included check
  45478. if (light._includedOnlyMeshesIds.length > 0) {
  45479. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  45480. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  45481. if (includedOnlyMesh) {
  45482. light.includedOnlyMeshes.push(includedOnlyMesh);
  45483. }
  45484. }
  45485. light._includedOnlyMeshesIds = [];
  45486. }
  45487. }
  45488. // Actions (scene)
  45489. if (parsedData.actions) {
  45490. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  45491. }
  45492. // Finish
  45493. return true;
  45494. }
  45495. catch (err) {
  45496. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  45497. log = null;
  45498. throw err;
  45499. }
  45500. finally {
  45501. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  45502. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  45503. }
  45504. }
  45505. }
  45506. });
  45507. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45508. })(BABYLON || (BABYLON = {}));
  45509. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  45510. var BABYLON;
  45511. (function (BABYLON) {
  45512. var FilesInput = (function () {
  45513. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  45514. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  45515. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  45516. this._engine = p_engine;
  45517. this._canvas = p_canvas;
  45518. this._currentScene = p_scene;
  45519. this._sceneLoadedCallback = p_sceneLoadedCallback;
  45520. this._progressCallback = p_progressCallback;
  45521. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  45522. this._textureLoadingCallback = p_textureLoadingCallback;
  45523. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  45524. }
  45525. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  45526. var _this = this;
  45527. if (p_elementToMonitor) {
  45528. this._elementToMonitor = p_elementToMonitor;
  45529. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  45530. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  45531. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  45532. }
  45533. };
  45534. FilesInput.prototype.renderFunction = function () {
  45535. if (this._additionnalRenderLoopLogicCallback) {
  45536. this._additionnalRenderLoopLogicCallback();
  45537. }
  45538. if (this._currentScene) {
  45539. if (this._textureLoadingCallback) {
  45540. var remaining = this._currentScene.getWaitingItemsCount();
  45541. if (remaining > 0) {
  45542. this._textureLoadingCallback(remaining);
  45543. }
  45544. }
  45545. this._currentScene.render();
  45546. }
  45547. };
  45548. FilesInput.prototype.drag = function (e) {
  45549. e.stopPropagation();
  45550. e.preventDefault();
  45551. };
  45552. FilesInput.prototype.drop = function (eventDrop) {
  45553. eventDrop.stopPropagation();
  45554. eventDrop.preventDefault();
  45555. this.loadFiles(eventDrop);
  45556. };
  45557. FilesInput.prototype.loadFiles = function (event) {
  45558. if (this._startingProcessingFilesCallback)
  45559. this._startingProcessingFilesCallback();
  45560. // Handling data transfer via drag'n'drop
  45561. if (event && event.dataTransfer && event.dataTransfer.files) {
  45562. this._filesToLoad = event.dataTransfer.files;
  45563. }
  45564. // Handling files from input files
  45565. if (event && event.target && event.target.files) {
  45566. this._filesToLoad = event.target.files;
  45567. }
  45568. if (this._filesToLoad && this._filesToLoad.length > 0) {
  45569. for (var i = 0; i < this._filesToLoad.length; i++) {
  45570. var name_1 = this._filesToLoad[i].name.toLowerCase();
  45571. var extension = name_1.split('.').pop();
  45572. var type = this._filesToLoad[i].type;
  45573. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  45574. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  45575. this._sceneFileToLoad = this._filesToLoad[i];
  45576. }
  45577. else {
  45578. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  45579. }
  45580. }
  45581. this.reload();
  45582. }
  45583. };
  45584. FilesInput.prototype.reload = function () {
  45585. var _this = this;
  45586. var that = this;
  45587. // If a ".babylon" file has been provided
  45588. if (this._sceneFileToLoad) {
  45589. if (this._currentScene) {
  45590. if (BABYLON.Tools.errorsCount > 0) {
  45591. BABYLON.Tools.ClearLogCache();
  45592. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  45593. }
  45594. this._engine.stopRenderLoop();
  45595. this._currentScene.dispose();
  45596. }
  45597. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  45598. that._currentScene = newScene;
  45599. // Wait for textures and shaders to be ready
  45600. that._currentScene.executeWhenReady(function () {
  45601. if (that._sceneLoadedCallback) {
  45602. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  45603. }
  45604. that._engine.runRenderLoop(function () { that.renderFunction(); });
  45605. });
  45606. }, function (progress) {
  45607. if (_this._progressCallback) {
  45608. _this._progressCallback(progress);
  45609. }
  45610. });
  45611. }
  45612. else {
  45613. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  45614. }
  45615. };
  45616. return FilesInput;
  45617. }());
  45618. FilesInput.FilesToLoad = new Array();
  45619. BABYLON.FilesInput = FilesInput;
  45620. })(BABYLON || (BABYLON = {}));
  45621. //# sourceMappingURL=babylon.filesInput.js.map
  45622. var BABYLON;
  45623. (function (BABYLON) {
  45624. /**
  45625. * This class implement a typical dictionary using a string as key and the generic type T as value.
  45626. * The underlying implementation relies on an associative array to ensure the best performances.
  45627. * The value can be anything including 'null' but except 'undefined'
  45628. */
  45629. var StringDictionary = (function () {
  45630. function StringDictionary() {
  45631. this._count = 0;
  45632. this._data = {};
  45633. }
  45634. /**
  45635. * This will clear this dictionary and copy the content from the 'source' one.
  45636. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  45637. * @param source the dictionary to take the content from and copy to this dictionary
  45638. */
  45639. StringDictionary.prototype.copyFrom = function (source) {
  45640. var _this = this;
  45641. this.clear();
  45642. source.forEach(function (t, v) { return _this.add(t, v); });
  45643. };
  45644. /**
  45645. * Get a value based from its key
  45646. * @param key the given key to get the matching value from
  45647. * @return the value if found, otherwise undefined is returned
  45648. */
  45649. StringDictionary.prototype.get = function (key) {
  45650. var val = this._data[key];
  45651. if (val !== undefined) {
  45652. return val;
  45653. }
  45654. return undefined;
  45655. };
  45656. /**
  45657. * Get a value from its key or add it if it doesn't exist.
  45658. * This method will ensure you that a given key/data will be present in the dictionary.
  45659. * @param key the given key to get the matching value from
  45660. * @param factory the factory that will create the value if the key is not present in the dictionary.
  45661. * The factory will only be invoked if there's no data for the given key.
  45662. * @return the value corresponding to the key.
  45663. */
  45664. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  45665. var val = this.get(key);
  45666. if (val !== undefined) {
  45667. return val;
  45668. }
  45669. val = factory(key);
  45670. if (val) {
  45671. this.add(key, val);
  45672. }
  45673. return val;
  45674. };
  45675. /**
  45676. * Get a value from its key if present in the dictionary otherwise add it
  45677. * @param key the key to get the value from
  45678. * @param val if there's no such key/value pair in the dictionary add it with this value
  45679. * @return the value corresponding to the key
  45680. */
  45681. StringDictionary.prototype.getOrAdd = function (key, val) {
  45682. var curVal = this.get(key);
  45683. if (curVal !== undefined) {
  45684. return curVal;
  45685. }
  45686. this.add(key, val);
  45687. return val;
  45688. };
  45689. /**
  45690. * Check if there's a given key in the dictionary
  45691. * @param key the key to check for
  45692. * @return true if the key is present, false otherwise
  45693. */
  45694. StringDictionary.prototype.contains = function (key) {
  45695. return this._data[key] !== undefined;
  45696. };
  45697. /**
  45698. * Add a new key and its corresponding value
  45699. * @param key the key to add
  45700. * @param value the value corresponding to the key
  45701. * @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
  45702. */
  45703. StringDictionary.prototype.add = function (key, value) {
  45704. if (this._data[key] !== undefined) {
  45705. return false;
  45706. }
  45707. this._data[key] = value;
  45708. ++this._count;
  45709. return true;
  45710. };
  45711. StringDictionary.prototype.set = function (key, value) {
  45712. if (this._data[key] === undefined) {
  45713. return false;
  45714. }
  45715. this._data[key] = value;
  45716. return true;
  45717. };
  45718. /**
  45719. * Get the element of the given key and remove it from the dictionary
  45720. * @param key
  45721. */
  45722. StringDictionary.prototype.getAndRemove = function (key) {
  45723. var val = this.get(key);
  45724. if (val !== undefined) {
  45725. delete this._data[key];
  45726. --this._count;
  45727. return val;
  45728. }
  45729. return null;
  45730. };
  45731. /**
  45732. * Remove a key/value from the dictionary.
  45733. * @param key the key to remove
  45734. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  45735. */
  45736. StringDictionary.prototype.remove = function (key) {
  45737. if (this.contains(key)) {
  45738. delete this._data[key];
  45739. --this._count;
  45740. return true;
  45741. }
  45742. return false;
  45743. };
  45744. /**
  45745. * Clear the whole content of the dictionary
  45746. */
  45747. StringDictionary.prototype.clear = function () {
  45748. this._data = {};
  45749. this._count = 0;
  45750. };
  45751. Object.defineProperty(StringDictionary.prototype, "count", {
  45752. get: function () {
  45753. return this._count;
  45754. },
  45755. enumerable: true,
  45756. configurable: true
  45757. });
  45758. /**
  45759. * Execute a callback on each key/val of the dictionary.
  45760. * Note that you can remove any element in this dictionary in the callback implementation
  45761. * @param callback the callback to execute on a given key/value pair
  45762. */
  45763. StringDictionary.prototype.forEach = function (callback) {
  45764. for (var cur in this._data) {
  45765. var val = this._data[cur];
  45766. callback(cur, val);
  45767. }
  45768. };
  45769. /**
  45770. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  45771. * If the callback returns null or undefined the method will iterate to the next key/value pair
  45772. * Note that you can remove any element in this dictionary in the callback implementation
  45773. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  45774. */
  45775. StringDictionary.prototype.first = function (callback) {
  45776. for (var cur in this._data) {
  45777. var val = this._data[cur];
  45778. var res = callback(cur, val);
  45779. if (res) {
  45780. return res;
  45781. }
  45782. }
  45783. return null;
  45784. };
  45785. return StringDictionary;
  45786. }());
  45787. BABYLON.StringDictionary = StringDictionary;
  45788. })(BABYLON || (BABYLON = {}));
  45789. //# sourceMappingURL=babylon.stringDictionary.js.map
  45790. var BABYLON;
  45791. (function (BABYLON) {
  45792. var Tags = (function () {
  45793. function Tags() {
  45794. }
  45795. Tags.EnableFor = function (obj) {
  45796. obj._tags = obj._tags || {};
  45797. obj.hasTags = function () {
  45798. return Tags.HasTags(obj);
  45799. };
  45800. obj.addTags = function (tagsString) {
  45801. return Tags.AddTagsTo(obj, tagsString);
  45802. };
  45803. obj.removeTags = function (tagsString) {
  45804. return Tags.RemoveTagsFrom(obj, tagsString);
  45805. };
  45806. obj.matchesTagsQuery = function (tagsQuery) {
  45807. return Tags.MatchesQuery(obj, tagsQuery);
  45808. };
  45809. };
  45810. Tags.DisableFor = function (obj) {
  45811. delete obj._tags;
  45812. delete obj.hasTags;
  45813. delete obj.addTags;
  45814. delete obj.removeTags;
  45815. delete obj.matchesTagsQuery;
  45816. };
  45817. Tags.HasTags = function (obj) {
  45818. if (!obj._tags) {
  45819. return false;
  45820. }
  45821. return !BABYLON.Tools.IsEmpty(obj._tags);
  45822. };
  45823. Tags.GetTags = function (obj, asString) {
  45824. if (asString === void 0) { asString = true; }
  45825. if (!obj._tags) {
  45826. return null;
  45827. }
  45828. if (asString) {
  45829. var tagsArray = [];
  45830. for (var tag in obj._tags) {
  45831. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  45832. tagsArray.push(tag);
  45833. }
  45834. }
  45835. return tagsArray.join(" ");
  45836. }
  45837. else {
  45838. return obj._tags;
  45839. }
  45840. };
  45841. // the tags 'true' and 'false' are reserved and cannot be used as tags
  45842. // a tag cannot start with '||', '&&', and '!'
  45843. // it cannot contain whitespaces
  45844. Tags.AddTagsTo = function (obj, tagsString) {
  45845. if (!tagsString) {
  45846. return;
  45847. }
  45848. if (typeof tagsString !== "string") {
  45849. return;
  45850. }
  45851. var tags = tagsString.split(" ");
  45852. tags.forEach(function (tag, index, array) {
  45853. Tags._AddTagTo(obj, tag);
  45854. });
  45855. };
  45856. Tags._AddTagTo = function (obj, tag) {
  45857. tag = tag.trim();
  45858. if (tag === "" || tag === "true" || tag === "false") {
  45859. return;
  45860. }
  45861. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  45862. return;
  45863. }
  45864. Tags.EnableFor(obj);
  45865. obj._tags[tag] = true;
  45866. };
  45867. Tags.RemoveTagsFrom = function (obj, tagsString) {
  45868. if (!Tags.HasTags(obj)) {
  45869. return;
  45870. }
  45871. var tags = tagsString.split(" ");
  45872. for (var t in tags) {
  45873. Tags._RemoveTagFrom(obj, tags[t]);
  45874. }
  45875. };
  45876. Tags._RemoveTagFrom = function (obj, tag) {
  45877. delete obj._tags[tag];
  45878. };
  45879. Tags.MatchesQuery = function (obj, tagsQuery) {
  45880. if (tagsQuery === undefined) {
  45881. return true;
  45882. }
  45883. if (tagsQuery === "") {
  45884. return Tags.HasTags(obj);
  45885. }
  45886. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  45887. };
  45888. return Tags;
  45889. }());
  45890. BABYLON.Tags = Tags;
  45891. })(BABYLON || (BABYLON = {}));
  45892. //# sourceMappingURL=babylon.tags.js.map
  45893. var BABYLON;
  45894. (function (BABYLON) {
  45895. var Internals;
  45896. (function (Internals) {
  45897. var AndOrNotEvaluator = (function () {
  45898. function AndOrNotEvaluator() {
  45899. }
  45900. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  45901. if (!query.match(/\([^\(\)]*\)/g)) {
  45902. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  45903. }
  45904. else {
  45905. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  45906. // remove parenthesis
  45907. r = r.slice(1, r.length - 1);
  45908. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  45909. });
  45910. }
  45911. if (query === "true") {
  45912. return true;
  45913. }
  45914. if (query === "false") {
  45915. return false;
  45916. }
  45917. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  45918. };
  45919. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  45920. evaluateCallback = evaluateCallback || (function (r) {
  45921. return r === "true" ? true : false;
  45922. });
  45923. var result;
  45924. var or = parenthesisContent.split("||");
  45925. for (var i in or) {
  45926. if (or.hasOwnProperty(i)) {
  45927. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  45928. var and = ori.split("&&");
  45929. if (and.length > 1) {
  45930. for (var j = 0; j < and.length; ++j) {
  45931. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  45932. if (andj !== "true" && andj !== "false") {
  45933. if (andj[0] === "!") {
  45934. result = !evaluateCallback(andj.substring(1));
  45935. }
  45936. else {
  45937. result = evaluateCallback(andj);
  45938. }
  45939. }
  45940. else {
  45941. result = andj === "true" ? true : false;
  45942. }
  45943. if (!result) {
  45944. ori = "false";
  45945. break;
  45946. }
  45947. }
  45948. }
  45949. if (result || ori === "true") {
  45950. result = true;
  45951. break;
  45952. }
  45953. // result equals false (or undefined)
  45954. if (ori !== "true" && ori !== "false") {
  45955. if (ori[0] === "!") {
  45956. result = !evaluateCallback(ori.substring(1));
  45957. }
  45958. else {
  45959. result = evaluateCallback(ori);
  45960. }
  45961. }
  45962. else {
  45963. result = ori === "true" ? true : false;
  45964. }
  45965. }
  45966. }
  45967. // the whole parenthesis scope is replaced by 'true' or 'false'
  45968. return result ? "true" : "false";
  45969. };
  45970. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  45971. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  45972. // remove whitespaces
  45973. r = r.replace(/[\s]/g, function () { return ""; });
  45974. return r.length % 2 ? "!" : "";
  45975. });
  45976. booleanString = booleanString.trim();
  45977. if (booleanString === "!true") {
  45978. booleanString = "false";
  45979. }
  45980. else if (booleanString === "!false") {
  45981. booleanString = "true";
  45982. }
  45983. return booleanString;
  45984. };
  45985. return AndOrNotEvaluator;
  45986. }());
  45987. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  45988. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45989. })(BABYLON || (BABYLON = {}));
  45990. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  45991. var BABYLON;
  45992. (function (BABYLON) {
  45993. var Database = (function () {
  45994. function Database(urlToScene, callbackManifestChecked) {
  45995. // Handling various flavors of prefixed version of IndexedDB
  45996. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  45997. this.callbackManifestChecked = callbackManifestChecked;
  45998. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  45999. this.db = null;
  46000. this.enableSceneOffline = false;
  46001. this.enableTexturesOffline = false;
  46002. this.manifestVersionFound = 0;
  46003. this.mustUpdateRessources = false;
  46004. this.hasReachedQuota = false;
  46005. if (!Database.IDBStorageEnabled) {
  46006. this.callbackManifestChecked(true);
  46007. }
  46008. else {
  46009. this.checkManifestFile();
  46010. }
  46011. }
  46012. Database.prototype.checkManifestFile = function () {
  46013. var _this = this;
  46014. function noManifestFile() {
  46015. that.enableSceneOffline = false;
  46016. that.enableTexturesOffline = false;
  46017. that.callbackManifestChecked(false);
  46018. }
  46019. var that = this;
  46020. var timeStampUsed = false;
  46021. var manifestURL = this.currentSceneUrl + ".manifest";
  46022. var xhr = new XMLHttpRequest();
  46023. if (navigator.onLine) {
  46024. // Adding a timestamp to by-pass browsers' cache
  46025. timeStampUsed = true;
  46026. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  46027. }
  46028. xhr.open("GET", manifestURL, true);
  46029. xhr.addEventListener("load", function () {
  46030. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  46031. try {
  46032. var manifestFile = JSON.parse(xhr.response);
  46033. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  46034. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  46035. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  46036. _this.manifestVersionFound = manifestFile.version;
  46037. }
  46038. if (_this.callbackManifestChecked) {
  46039. _this.callbackManifestChecked(true);
  46040. }
  46041. }
  46042. catch (ex) {
  46043. noManifestFile();
  46044. }
  46045. }
  46046. else {
  46047. noManifestFile();
  46048. }
  46049. }, false);
  46050. xhr.addEventListener("error", function (event) {
  46051. if (timeStampUsed) {
  46052. timeStampUsed = false;
  46053. // Let's retry without the timeStamp
  46054. // It could fail when coupled with HTML5 Offline API
  46055. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  46056. xhr.open("GET", retryManifestURL, true);
  46057. xhr.send();
  46058. }
  46059. else {
  46060. noManifestFile();
  46061. }
  46062. }, false);
  46063. try {
  46064. xhr.send();
  46065. }
  46066. catch (ex) {
  46067. BABYLON.Tools.Error("Error on XHR send request.");
  46068. that.callbackManifestChecked(false);
  46069. }
  46070. };
  46071. Database.prototype.openAsync = function (successCallback, errorCallback) {
  46072. var _this = this;
  46073. function handleError() {
  46074. that.isSupported = false;
  46075. if (errorCallback)
  46076. errorCallback();
  46077. }
  46078. var that = this;
  46079. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  46080. // Your browser doesn't support IndexedDB
  46081. this.isSupported = false;
  46082. if (errorCallback)
  46083. errorCallback();
  46084. }
  46085. else {
  46086. // If the DB hasn't been opened or created yet
  46087. if (!this.db) {
  46088. this.hasReachedQuota = false;
  46089. this.isSupported = true;
  46090. var request = this.idbFactory.open("babylonjs", 1);
  46091. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  46092. request.onerror = function (event) {
  46093. handleError();
  46094. };
  46095. // executes when a version change transaction cannot complete due to other active transactions
  46096. request.onblocked = function (event) {
  46097. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  46098. handleError();
  46099. };
  46100. // DB has been opened successfully
  46101. request.onsuccess = function (event) {
  46102. _this.db = request.result;
  46103. successCallback();
  46104. };
  46105. // Initialization of the DB. Creating Scenes & Textures stores
  46106. request.onupgradeneeded = function (event) {
  46107. _this.db = (event.target).result;
  46108. try {
  46109. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  46110. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  46111. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  46112. }
  46113. catch (ex) {
  46114. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  46115. handleError();
  46116. }
  46117. };
  46118. }
  46119. else {
  46120. if (successCallback)
  46121. successCallback();
  46122. }
  46123. }
  46124. };
  46125. Database.prototype.loadImageFromDB = function (url, image) {
  46126. var _this = this;
  46127. var completeURL = Database.ReturnFullUrlLocation(url);
  46128. var saveAndLoadImage = function () {
  46129. if (!_this.hasReachedQuota && _this.db !== null) {
  46130. // the texture is not yet in the DB, let's try to save it
  46131. _this._saveImageIntoDBAsync(completeURL, image);
  46132. }
  46133. else {
  46134. image.src = url;
  46135. }
  46136. };
  46137. if (!this.mustUpdateRessources) {
  46138. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  46139. }
  46140. else {
  46141. saveAndLoadImage();
  46142. }
  46143. };
  46144. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  46145. if (this.isSupported && this.db !== null) {
  46146. var texture;
  46147. var transaction = this.db.transaction(["textures"]);
  46148. transaction.onabort = function (event) {
  46149. image.src = url;
  46150. };
  46151. transaction.oncomplete = function (event) {
  46152. var blobTextureURL;
  46153. if (texture) {
  46154. var URL = window.URL || window.webkitURL;
  46155. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  46156. image.onerror = function () {
  46157. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  46158. image.src = url;
  46159. };
  46160. image.src = blobTextureURL;
  46161. }
  46162. else {
  46163. notInDBCallback();
  46164. }
  46165. };
  46166. var getRequest = transaction.objectStore("textures").get(url);
  46167. getRequest.onsuccess = function (event) {
  46168. texture = (event.target).result;
  46169. };
  46170. getRequest.onerror = function (event) {
  46171. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  46172. image.src = url;
  46173. };
  46174. }
  46175. else {
  46176. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46177. image.src = url;
  46178. }
  46179. };
  46180. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  46181. var _this = this;
  46182. if (this.isSupported) {
  46183. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  46184. var generateBlobUrl = function () {
  46185. var blobTextureURL;
  46186. if (blob) {
  46187. var URL = window.URL || window.webkitURL;
  46188. try {
  46189. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  46190. }
  46191. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  46192. catch (ex) {
  46193. blobTextureURL = URL.createObjectURL(blob);
  46194. }
  46195. }
  46196. image.src = blobTextureURL;
  46197. };
  46198. if (Database.IsUASupportingBlobStorage) {
  46199. var xhr = new XMLHttpRequest(), blob;
  46200. xhr.open("GET", url, true);
  46201. xhr.responseType = "blob";
  46202. xhr.addEventListener("load", function () {
  46203. if (xhr.status === 200) {
  46204. // Blob as response (XHR2)
  46205. blob = xhr.response;
  46206. var transaction = _this.db.transaction(["textures"], "readwrite");
  46207. // the transaction could abort because of a QuotaExceededError error
  46208. transaction.onabort = function (event) {
  46209. try {
  46210. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  46211. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  46212. _this.hasReachedQuota = true;
  46213. }
  46214. }
  46215. catch (ex) { }
  46216. generateBlobUrl();
  46217. };
  46218. transaction.oncomplete = function (event) {
  46219. generateBlobUrl();
  46220. };
  46221. var newTexture = { textureUrl: url, data: blob };
  46222. try {
  46223. // Put the blob into the dabase
  46224. var addRequest = transaction.objectStore("textures").put(newTexture);
  46225. addRequest.onsuccess = function (event) {
  46226. };
  46227. addRequest.onerror = function (event) {
  46228. generateBlobUrl();
  46229. };
  46230. }
  46231. catch (ex) {
  46232. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  46233. if (ex.code === 25) {
  46234. Database.IsUASupportingBlobStorage = false;
  46235. }
  46236. image.src = url;
  46237. }
  46238. }
  46239. else {
  46240. image.src = url;
  46241. }
  46242. }, false);
  46243. xhr.addEventListener("error", function (event) {
  46244. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  46245. image.src = url;
  46246. }, false);
  46247. xhr.send();
  46248. }
  46249. else {
  46250. image.src = url;
  46251. }
  46252. }
  46253. else {
  46254. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46255. image.src = url;
  46256. }
  46257. };
  46258. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  46259. var _this = this;
  46260. var updateVersion = function (event) {
  46261. // the version is not yet in the DB or we need to update it
  46262. _this._saveVersionIntoDBAsync(url, versionLoaded);
  46263. };
  46264. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  46265. };
  46266. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  46267. var _this = this;
  46268. if (this.isSupported) {
  46269. var version;
  46270. try {
  46271. var transaction = this.db.transaction(["versions"]);
  46272. transaction.oncomplete = function (event) {
  46273. if (version) {
  46274. // If the version in the JSON file is > than the version in DB
  46275. if (_this.manifestVersionFound > version.data) {
  46276. _this.mustUpdateRessources = true;
  46277. updateInDBCallback();
  46278. }
  46279. else {
  46280. callback(version.data);
  46281. }
  46282. }
  46283. else {
  46284. _this.mustUpdateRessources = true;
  46285. updateInDBCallback();
  46286. }
  46287. };
  46288. transaction.onabort = function (event) {
  46289. callback(-1);
  46290. };
  46291. var getRequest = transaction.objectStore("versions").get(url);
  46292. getRequest.onsuccess = function (event) {
  46293. version = (event.target).result;
  46294. };
  46295. getRequest.onerror = function (event) {
  46296. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  46297. callback(-1);
  46298. };
  46299. }
  46300. catch (ex) {
  46301. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  46302. callback(-1);
  46303. }
  46304. }
  46305. else {
  46306. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46307. callback(-1);
  46308. }
  46309. };
  46310. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  46311. var _this = this;
  46312. if (this.isSupported && !this.hasReachedQuota) {
  46313. try {
  46314. // Open a transaction to the database
  46315. var transaction = this.db.transaction(["versions"], "readwrite");
  46316. // the transaction could abort because of a QuotaExceededError error
  46317. transaction.onabort = function (event) {
  46318. try {
  46319. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  46320. _this.hasReachedQuota = true;
  46321. }
  46322. }
  46323. catch (ex) { }
  46324. callback(-1);
  46325. };
  46326. transaction.oncomplete = function (event) {
  46327. callback(_this.manifestVersionFound);
  46328. };
  46329. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  46330. // Put the scene into the database
  46331. var addRequest = transaction.objectStore("versions").put(newVersion);
  46332. addRequest.onsuccess = function (event) {
  46333. };
  46334. addRequest.onerror = function (event) {
  46335. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  46336. };
  46337. }
  46338. catch (ex) {
  46339. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  46340. callback(-1);
  46341. }
  46342. }
  46343. else {
  46344. callback(-1);
  46345. }
  46346. };
  46347. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  46348. var _this = this;
  46349. var completeUrl = Database.ReturnFullUrlLocation(url);
  46350. var saveAndLoadFile = function (event) {
  46351. // the scene is not yet in the DB, let's try to save it
  46352. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  46353. };
  46354. this._checkVersionFromDB(completeUrl, function (version) {
  46355. if (version !== -1) {
  46356. if (!_this.mustUpdateRessources) {
  46357. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  46358. }
  46359. else {
  46360. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  46361. }
  46362. }
  46363. else {
  46364. errorCallback();
  46365. }
  46366. });
  46367. };
  46368. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  46369. if (this.isSupported) {
  46370. var targetStore;
  46371. if (url.indexOf(".babylon") !== -1) {
  46372. targetStore = "scenes";
  46373. }
  46374. else {
  46375. targetStore = "textures";
  46376. }
  46377. var file;
  46378. var transaction = this.db.transaction([targetStore]);
  46379. transaction.oncomplete = function (event) {
  46380. if (file) {
  46381. callback(file.data);
  46382. }
  46383. else {
  46384. notInDBCallback();
  46385. }
  46386. };
  46387. transaction.onabort = function (event) {
  46388. notInDBCallback();
  46389. };
  46390. var getRequest = transaction.objectStore(targetStore).get(url);
  46391. getRequest.onsuccess = function (event) {
  46392. file = (event.target).result;
  46393. };
  46394. getRequest.onerror = function (event) {
  46395. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  46396. notInDBCallback();
  46397. };
  46398. }
  46399. else {
  46400. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46401. callback();
  46402. }
  46403. };
  46404. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  46405. var _this = this;
  46406. if (this.isSupported) {
  46407. var targetStore;
  46408. if (url.indexOf(".babylon") !== -1) {
  46409. targetStore = "scenes";
  46410. }
  46411. else {
  46412. targetStore = "textures";
  46413. }
  46414. // Create XHR
  46415. var xhr = new XMLHttpRequest(), fileData;
  46416. xhr.open("GET", url, true);
  46417. if (useArrayBuffer) {
  46418. xhr.responseType = "arraybuffer";
  46419. }
  46420. xhr.onprogress = progressCallback;
  46421. xhr.addEventListener("load", function () {
  46422. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  46423. // Blob as response (XHR2)
  46424. //fileData = xhr.responseText;
  46425. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  46426. if (!_this.hasReachedQuota) {
  46427. // Open a transaction to the database
  46428. var transaction = _this.db.transaction([targetStore], "readwrite");
  46429. // the transaction could abort because of a QuotaExceededError error
  46430. transaction.onabort = function (event) {
  46431. try {
  46432. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  46433. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  46434. _this.hasReachedQuota = true;
  46435. }
  46436. }
  46437. catch (ex) { }
  46438. callback(fileData);
  46439. };
  46440. transaction.oncomplete = function (event) {
  46441. callback(fileData);
  46442. };
  46443. var newFile;
  46444. if (targetStore === "scenes") {
  46445. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  46446. }
  46447. else {
  46448. newFile = { textureUrl: url, data: fileData };
  46449. }
  46450. try {
  46451. // Put the scene into the database
  46452. var addRequest = transaction.objectStore(targetStore).put(newFile);
  46453. addRequest.onsuccess = function (event) {
  46454. };
  46455. addRequest.onerror = function (event) {
  46456. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  46457. };
  46458. }
  46459. catch (ex) {
  46460. callback(fileData);
  46461. }
  46462. }
  46463. else {
  46464. callback(fileData);
  46465. }
  46466. }
  46467. else {
  46468. callback();
  46469. }
  46470. }, false);
  46471. xhr.addEventListener("error", function (event) {
  46472. BABYLON.Tools.Error("error on XHR request.");
  46473. callback();
  46474. }, false);
  46475. xhr.send();
  46476. }
  46477. else {
  46478. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46479. callback();
  46480. }
  46481. };
  46482. return Database;
  46483. }());
  46484. Database.IsUASupportingBlobStorage = true;
  46485. Database.IDBStorageEnabled = true;
  46486. Database.parseURL = function (url) {
  46487. var a = document.createElement('a');
  46488. a.href = url;
  46489. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  46490. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  46491. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  46492. return absLocation;
  46493. };
  46494. Database.ReturnFullUrlLocation = function (url) {
  46495. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  46496. return (Database.parseURL(window.location.href) + url);
  46497. }
  46498. else {
  46499. return url;
  46500. }
  46501. };
  46502. BABYLON.Database = Database;
  46503. })(BABYLON || (BABYLON = {}));
  46504. //# sourceMappingURL=babylon.database.js.map
  46505. var BABYLON;
  46506. (function (BABYLON) {
  46507. var FresnelParameters = (function () {
  46508. function FresnelParameters() {
  46509. this._isEnabled = true;
  46510. this.leftColor = BABYLON.Color3.White();
  46511. this.rightColor = BABYLON.Color3.Black();
  46512. this.bias = 0;
  46513. this.power = 1;
  46514. }
  46515. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  46516. get: function () {
  46517. return this._isEnabled;
  46518. },
  46519. set: function (value) {
  46520. if (this._isEnabled === value) {
  46521. return;
  46522. }
  46523. this._isEnabled = value;
  46524. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  46525. },
  46526. enumerable: true,
  46527. configurable: true
  46528. });
  46529. FresnelParameters.prototype.clone = function () {
  46530. var newFresnelParameters = new FresnelParameters();
  46531. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  46532. return newFresnelParameters;
  46533. };
  46534. FresnelParameters.prototype.serialize = function () {
  46535. var serializationObject = {};
  46536. serializationObject.isEnabled = this.isEnabled;
  46537. serializationObject.leftColor = this.leftColor;
  46538. serializationObject.rightColor = this.rightColor;
  46539. serializationObject.bias = this.bias;
  46540. serializationObject.power = this.power;
  46541. return serializationObject;
  46542. };
  46543. FresnelParameters.Parse = function (parsedFresnelParameters) {
  46544. var fresnelParameters = new FresnelParameters();
  46545. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  46546. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  46547. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  46548. fresnelParameters.bias = parsedFresnelParameters.bias;
  46549. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  46550. return fresnelParameters;
  46551. };
  46552. return FresnelParameters;
  46553. }());
  46554. BABYLON.FresnelParameters = FresnelParameters;
  46555. })(BABYLON || (BABYLON = {}));
  46556. //# sourceMappingURL=babylon.fresnelParameters.js.map
  46557. var BABYLON;
  46558. (function (BABYLON) {
  46559. var MultiMaterial = (function (_super) {
  46560. __extends(MultiMaterial, _super);
  46561. function MultiMaterial(name, scene) {
  46562. var _this = _super.call(this, name, scene, true) || this;
  46563. _this.subMaterials = new Array();
  46564. scene.multiMaterials.push(_this);
  46565. return _this;
  46566. }
  46567. // Properties
  46568. MultiMaterial.prototype.getSubMaterial = function (index) {
  46569. if (index < 0 || index >= this.subMaterials.length) {
  46570. return this.getScene().defaultMaterial;
  46571. }
  46572. return this.subMaterials[index];
  46573. };
  46574. // Methods
  46575. MultiMaterial.prototype.getClassName = function () {
  46576. return "MultiMaterial";
  46577. };
  46578. MultiMaterial.prototype.isReady = function (mesh) {
  46579. for (var index = 0; index < this.subMaterials.length; index++) {
  46580. var subMaterial = this.subMaterials[index];
  46581. if (subMaterial) {
  46582. if (!this.subMaterials[index].isReady(mesh)) {
  46583. return false;
  46584. }
  46585. }
  46586. }
  46587. return true;
  46588. };
  46589. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  46590. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  46591. for (var index = 0; index < this.subMaterials.length; index++) {
  46592. var subMaterial = null;
  46593. if (cloneChildren) {
  46594. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  46595. }
  46596. else {
  46597. subMaterial = this.subMaterials[index];
  46598. }
  46599. newMultiMaterial.subMaterials.push(subMaterial);
  46600. }
  46601. return newMultiMaterial;
  46602. };
  46603. MultiMaterial.prototype.serialize = function () {
  46604. var serializationObject = {};
  46605. serializationObject.name = this.name;
  46606. serializationObject.id = this.id;
  46607. serializationObject.tags = BABYLON.Tags.GetTags(this);
  46608. serializationObject.materials = [];
  46609. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  46610. var subMat = this.subMaterials[matIndex];
  46611. if (subMat) {
  46612. serializationObject.materials.push(subMat.id);
  46613. }
  46614. else {
  46615. serializationObject.materials.push(null);
  46616. }
  46617. }
  46618. return serializationObject;
  46619. };
  46620. return MultiMaterial;
  46621. }(BABYLON.Material));
  46622. BABYLON.MultiMaterial = MultiMaterial;
  46623. })(BABYLON || (BABYLON = {}));
  46624. //# sourceMappingURL=babylon.multiMaterial.js.map
  46625. var BABYLON;
  46626. (function (BABYLON) {
  46627. var FreeCameraTouchInput = (function () {
  46628. function FreeCameraTouchInput() {
  46629. this._offsetX = null;
  46630. this._offsetY = null;
  46631. this._pointerCount = 0;
  46632. this._pointerPressed = [];
  46633. this.touchAngularSensibility = 200000.0;
  46634. this.touchMoveSensibility = 250.0;
  46635. }
  46636. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  46637. var _this = this;
  46638. var previousPosition;
  46639. if (this._pointerInput === undefined) {
  46640. this._onLostFocus = function (evt) {
  46641. _this._offsetX = null;
  46642. _this._offsetY = null;
  46643. };
  46644. this._pointerInput = function (p, s) {
  46645. var evt = p.event;
  46646. if (evt.pointerType === "mouse") {
  46647. return;
  46648. }
  46649. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  46650. if (!noPreventDefault) {
  46651. evt.preventDefault();
  46652. }
  46653. _this._pointerPressed.push(evt.pointerId);
  46654. if (_this._pointerPressed.length !== 1) {
  46655. return;
  46656. }
  46657. previousPosition = {
  46658. x: evt.clientX,
  46659. y: evt.clientY
  46660. };
  46661. }
  46662. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  46663. if (!noPreventDefault) {
  46664. evt.preventDefault();
  46665. }
  46666. var index = _this._pointerPressed.indexOf(evt.pointerId);
  46667. if (index === -1) {
  46668. return;
  46669. }
  46670. _this._pointerPressed.splice(index, 1);
  46671. if (index != 0) {
  46672. return;
  46673. }
  46674. previousPosition = null;
  46675. _this._offsetX = null;
  46676. _this._offsetY = null;
  46677. }
  46678. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46679. if (!noPreventDefault) {
  46680. evt.preventDefault();
  46681. }
  46682. if (!previousPosition) {
  46683. return;
  46684. }
  46685. var index = _this._pointerPressed.indexOf(evt.pointerId);
  46686. if (index != 0) {
  46687. return;
  46688. }
  46689. _this._offsetX = evt.clientX - previousPosition.x;
  46690. _this._offsetY = -(evt.clientY - previousPosition.y);
  46691. }
  46692. };
  46693. }
  46694. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46695. element.addEventListener("blur", this._onLostFocus);
  46696. };
  46697. FreeCameraTouchInput.prototype.detachControl = function (element) {
  46698. if (this._pointerInput && element) {
  46699. this.camera.getScene().onPointerObservable.remove(this._observer);
  46700. this._observer = null;
  46701. element.removeEventListener("blur", this._onLostFocus);
  46702. this._onLostFocus = null;
  46703. this._pointerPressed = [];
  46704. this._offsetX = null;
  46705. this._offsetY = null;
  46706. this._pointerCount = 0;
  46707. }
  46708. };
  46709. FreeCameraTouchInput.prototype.checkInputs = function () {
  46710. if (this._offsetX) {
  46711. var camera = this.camera;
  46712. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  46713. if (this._pointerPressed.length > 1) {
  46714. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  46715. }
  46716. else {
  46717. var speed = camera._computeLocalCameraSpeed();
  46718. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  46719. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  46720. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  46721. }
  46722. }
  46723. };
  46724. FreeCameraTouchInput.prototype.getTypeName = function () {
  46725. return "FreeCameraTouchInput";
  46726. };
  46727. FreeCameraTouchInput.prototype.getSimpleName = function () {
  46728. return "touch";
  46729. };
  46730. return FreeCameraTouchInput;
  46731. }());
  46732. __decorate([
  46733. BABYLON.serialize()
  46734. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  46735. __decorate([
  46736. BABYLON.serialize()
  46737. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  46738. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  46739. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  46740. })(BABYLON || (BABYLON = {}));
  46741. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  46742. /// <reference path="babylon.freeCamera.ts" />
  46743. var BABYLON;
  46744. (function (BABYLON) {
  46745. // We're mainly based on the logic defined into the FreeCamera code
  46746. var TouchCamera = (function (_super) {
  46747. __extends(TouchCamera, _super);
  46748. //-- end properties for backward compatibility for inputs
  46749. function TouchCamera(name, position, scene) {
  46750. var _this = _super.call(this, name, position, scene) || this;
  46751. _this.inputs.addTouch();
  46752. _this._setupInputs();
  46753. return _this;
  46754. }
  46755. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  46756. //-- Begin properties for backward compatibility for inputs
  46757. get: function () {
  46758. var touch = this.inputs.attached["touch"];
  46759. if (touch)
  46760. return touch.touchAngularSensibility;
  46761. },
  46762. set: function (value) {
  46763. var touch = this.inputs.attached["touch"];
  46764. if (touch)
  46765. touch.touchAngularSensibility = value;
  46766. },
  46767. enumerable: true,
  46768. configurable: true
  46769. });
  46770. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  46771. get: function () {
  46772. var touch = this.inputs.attached["touch"];
  46773. if (touch)
  46774. return touch.touchMoveSensibility;
  46775. },
  46776. set: function (value) {
  46777. var touch = this.inputs.attached["touch"];
  46778. if (touch)
  46779. touch.touchMoveSensibility = value;
  46780. },
  46781. enumerable: true,
  46782. configurable: true
  46783. });
  46784. TouchCamera.prototype.getClassName = function () {
  46785. return "TouchCamera";
  46786. };
  46787. TouchCamera.prototype._setupInputs = function () {
  46788. var mouse = this.inputs.attached["mouse"];
  46789. if (mouse) {
  46790. mouse.touchEnabled = false;
  46791. }
  46792. };
  46793. return TouchCamera;
  46794. }(BABYLON.FreeCamera));
  46795. BABYLON.TouchCamera = TouchCamera;
  46796. })(BABYLON || (BABYLON = {}));
  46797. //# sourceMappingURL=babylon.touchCamera.js.map
  46798. var BABYLON;
  46799. (function (BABYLON) {
  46800. var ProceduralTexture = (function (_super) {
  46801. __extends(ProceduralTexture, _super);
  46802. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  46803. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46804. if (isCube === void 0) { isCube = false; }
  46805. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  46806. _this.isCube = isCube;
  46807. _this.isEnabled = true;
  46808. _this._currentRefreshId = -1;
  46809. _this._refreshRate = 1;
  46810. _this._vertexBuffers = {};
  46811. _this._uniforms = new Array();
  46812. _this._samplers = new Array();
  46813. _this._textures = new Array();
  46814. _this._floats = new Array();
  46815. _this._floatsArrays = {};
  46816. _this._colors3 = new Array();
  46817. _this._colors4 = new Array();
  46818. _this._vectors2 = new Array();
  46819. _this._vectors3 = new Array();
  46820. _this._matrices = new Array();
  46821. _this._fallbackTextureUsed = false;
  46822. scene._proceduralTextures.push(_this);
  46823. _this.name = name;
  46824. _this.isRenderTarget = true;
  46825. _this._size = size;
  46826. _this._generateMipMaps = generateMipMaps;
  46827. _this.setFragment(fragment);
  46828. _this._fallbackTexture = fallbackTexture;
  46829. var engine = scene.getEngine();
  46830. if (isCube) {
  46831. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  46832. _this.setFloat("face", 0);
  46833. }
  46834. else {
  46835. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  46836. }
  46837. // VBO
  46838. var vertices = [];
  46839. vertices.push(1, 1);
  46840. vertices.push(-1, 1);
  46841. vertices.push(-1, -1);
  46842. vertices.push(1, -1);
  46843. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  46844. // Indices
  46845. var indices = [];
  46846. indices.push(0);
  46847. indices.push(1);
  46848. indices.push(2);
  46849. indices.push(0);
  46850. indices.push(2);
  46851. indices.push(3);
  46852. _this._indexBuffer = engine.createIndexBuffer(indices);
  46853. return _this;
  46854. }
  46855. ProceduralTexture.prototype.reset = function () {
  46856. if (this._effect === undefined) {
  46857. return;
  46858. }
  46859. var engine = this.getScene().getEngine();
  46860. engine._releaseEffect(this._effect);
  46861. };
  46862. ProceduralTexture.prototype.isReady = function () {
  46863. var _this = this;
  46864. var engine = this.getScene().getEngine();
  46865. var shaders;
  46866. if (!this._fragment) {
  46867. return false;
  46868. }
  46869. if (this._fallbackTextureUsed) {
  46870. return true;
  46871. }
  46872. if (this._fragment.fragmentElement !== undefined) {
  46873. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  46874. }
  46875. else {
  46876. shaders = { vertex: "procedural", fragment: this._fragment };
  46877. }
  46878. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  46879. _this.releaseInternalTexture();
  46880. if (_this._fallbackTexture) {
  46881. _this._texture = _this._fallbackTexture._texture;
  46882. _this._texture.references++;
  46883. }
  46884. _this._fallbackTextureUsed = true;
  46885. });
  46886. return this._effect.isReady();
  46887. };
  46888. ProceduralTexture.prototype.resetRefreshCounter = function () {
  46889. this._currentRefreshId = -1;
  46890. };
  46891. ProceduralTexture.prototype.setFragment = function (fragment) {
  46892. this._fragment = fragment;
  46893. };
  46894. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  46895. get: function () {
  46896. return this._refreshRate;
  46897. },
  46898. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  46899. set: function (value) {
  46900. this._refreshRate = value;
  46901. this.resetRefreshCounter();
  46902. },
  46903. enumerable: true,
  46904. configurable: true
  46905. });
  46906. ProceduralTexture.prototype._shouldRender = function () {
  46907. if (!this.isEnabled || !this.isReady() || !this._texture) {
  46908. return false;
  46909. }
  46910. if (this._fallbackTextureUsed) {
  46911. return false;
  46912. }
  46913. if (this._currentRefreshId === -1) {
  46914. this._currentRefreshId = 1;
  46915. return true;
  46916. }
  46917. if (this.refreshRate === this._currentRefreshId) {
  46918. this._currentRefreshId = 1;
  46919. return true;
  46920. }
  46921. this._currentRefreshId++;
  46922. return false;
  46923. };
  46924. ProceduralTexture.prototype.getRenderSize = function () {
  46925. return this._size;
  46926. };
  46927. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  46928. if (this._fallbackTextureUsed) {
  46929. return;
  46930. }
  46931. this.releaseInternalTexture();
  46932. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  46933. };
  46934. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  46935. if (this._uniforms.indexOf(uniformName) === -1) {
  46936. this._uniforms.push(uniformName);
  46937. }
  46938. };
  46939. ProceduralTexture.prototype.setTexture = function (name, texture) {
  46940. if (this._samplers.indexOf(name) === -1) {
  46941. this._samplers.push(name);
  46942. }
  46943. this._textures[name] = texture;
  46944. return this;
  46945. };
  46946. ProceduralTexture.prototype.setFloat = function (name, value) {
  46947. this._checkUniform(name);
  46948. this._floats[name] = value;
  46949. return this;
  46950. };
  46951. ProceduralTexture.prototype.setFloats = function (name, value) {
  46952. this._checkUniform(name);
  46953. this._floatsArrays[name] = value;
  46954. return this;
  46955. };
  46956. ProceduralTexture.prototype.setColor3 = function (name, value) {
  46957. this._checkUniform(name);
  46958. this._colors3[name] = value;
  46959. return this;
  46960. };
  46961. ProceduralTexture.prototype.setColor4 = function (name, value) {
  46962. this._checkUniform(name);
  46963. this._colors4[name] = value;
  46964. return this;
  46965. };
  46966. ProceduralTexture.prototype.setVector2 = function (name, value) {
  46967. this._checkUniform(name);
  46968. this._vectors2[name] = value;
  46969. return this;
  46970. };
  46971. ProceduralTexture.prototype.setVector3 = function (name, value) {
  46972. this._checkUniform(name);
  46973. this._vectors3[name] = value;
  46974. return this;
  46975. };
  46976. ProceduralTexture.prototype.setMatrix = function (name, value) {
  46977. this._checkUniform(name);
  46978. this._matrices[name] = value;
  46979. return this;
  46980. };
  46981. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  46982. var scene = this.getScene();
  46983. var engine = scene.getEngine();
  46984. // Render
  46985. engine.enableEffect(this._effect);
  46986. engine.setState(false);
  46987. // Texture
  46988. for (var name in this._textures) {
  46989. this._effect.setTexture(name, this._textures[name]);
  46990. }
  46991. // Float
  46992. for (name in this._floats) {
  46993. this._effect.setFloat(name, this._floats[name]);
  46994. }
  46995. // Floats
  46996. for (name in this._floatsArrays) {
  46997. this._effect.setArray(name, this._floatsArrays[name]);
  46998. }
  46999. // Color3
  47000. for (name in this._colors3) {
  47001. this._effect.setColor3(name, this._colors3[name]);
  47002. }
  47003. // Color4
  47004. for (name in this._colors4) {
  47005. var color = this._colors4[name];
  47006. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47007. }
  47008. // Vector2
  47009. for (name in this._vectors2) {
  47010. this._effect.setVector2(name, this._vectors2[name]);
  47011. }
  47012. // Vector3
  47013. for (name in this._vectors3) {
  47014. this._effect.setVector3(name, this._vectors3[name]);
  47015. }
  47016. // Matrix
  47017. for (name in this._matrices) {
  47018. this._effect.setMatrix(name, this._matrices[name]);
  47019. }
  47020. if (this.isCube) {
  47021. for (var face = 0; face < 6; face++) {
  47022. engine.bindFramebuffer(this._texture, face);
  47023. // VBOs
  47024. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  47025. this._effect.setFloat("face", face);
  47026. // Clear
  47027. engine.clear(scene.clearColor, true, true, true);
  47028. // Draw order
  47029. engine.draw(true, 0, 6);
  47030. // Mipmaps
  47031. if (face === 5) {
  47032. engine.generateMipMapsForCubemap(this._texture);
  47033. }
  47034. }
  47035. }
  47036. else {
  47037. engine.bindFramebuffer(this._texture);
  47038. // VBOs
  47039. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  47040. // Clear
  47041. engine.clear(scene.clearColor, true, true, true);
  47042. // Draw order
  47043. engine.draw(true, 0, 6);
  47044. }
  47045. // Unbind
  47046. engine.unBindFramebuffer(this._texture, this.isCube);
  47047. if (this.onGenerated) {
  47048. this.onGenerated();
  47049. }
  47050. };
  47051. ProceduralTexture.prototype.clone = function () {
  47052. var textureSize = this.getSize();
  47053. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  47054. // Base texture
  47055. newTexture.hasAlpha = this.hasAlpha;
  47056. newTexture.level = this.level;
  47057. // RenderTarget Texture
  47058. newTexture.coordinatesMode = this.coordinatesMode;
  47059. return newTexture;
  47060. };
  47061. ProceduralTexture.prototype.dispose = function () {
  47062. var index = this.getScene()._proceduralTextures.indexOf(this);
  47063. if (index >= 0) {
  47064. this.getScene()._proceduralTextures.splice(index, 1);
  47065. }
  47066. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47067. if (vertexBuffer) {
  47068. vertexBuffer.dispose();
  47069. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47070. }
  47071. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  47072. this._indexBuffer = null;
  47073. }
  47074. _super.prototype.dispose.call(this);
  47075. };
  47076. return ProceduralTexture;
  47077. }(BABYLON.Texture));
  47078. BABYLON.ProceduralTexture = ProceduralTexture;
  47079. })(BABYLON || (BABYLON = {}));
  47080. //# sourceMappingURL=babylon.proceduralTexture.js.map
  47081. /// <reference path="babylon.proceduralTexture.ts" />
  47082. var BABYLON;
  47083. (function (BABYLON) {
  47084. var CustomProceduralTexture = (function (_super) {
  47085. __extends(CustomProceduralTexture, _super);
  47086. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  47087. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  47088. _this._animate = true;
  47089. _this._time = 0;
  47090. _this._texturePath = texturePath;
  47091. //Try to load json
  47092. _this.loadJson(texturePath);
  47093. _this.refreshRate = 1;
  47094. return _this;
  47095. }
  47096. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  47097. var _this = this;
  47098. var that = this;
  47099. function noConfigFile() {
  47100. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  47101. try {
  47102. that.setFragment(that._texturePath);
  47103. }
  47104. catch (ex) {
  47105. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  47106. }
  47107. }
  47108. var configFileUrl = jsonUrl + "/config.json";
  47109. var xhr = new XMLHttpRequest();
  47110. xhr.open("GET", configFileUrl, true);
  47111. xhr.addEventListener("load", function () {
  47112. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  47113. try {
  47114. _this._config = JSON.parse(xhr.response);
  47115. _this.updateShaderUniforms();
  47116. _this.updateTextures();
  47117. _this.setFragment(_this._texturePath + "/custom");
  47118. _this._animate = _this._config.animate;
  47119. _this.refreshRate = _this._config.refreshrate;
  47120. }
  47121. catch (ex) {
  47122. noConfigFile();
  47123. }
  47124. }
  47125. else {
  47126. noConfigFile();
  47127. }
  47128. }, false);
  47129. xhr.addEventListener("error", function () {
  47130. noConfigFile();
  47131. }, false);
  47132. try {
  47133. xhr.send();
  47134. }
  47135. catch (ex) {
  47136. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  47137. }
  47138. };
  47139. CustomProceduralTexture.prototype.isReady = function () {
  47140. if (!_super.prototype.isReady.call(this)) {
  47141. return false;
  47142. }
  47143. for (var name in this._textures) {
  47144. var texture = this._textures[name];
  47145. if (!texture.isReady()) {
  47146. return false;
  47147. }
  47148. }
  47149. return true;
  47150. };
  47151. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  47152. if (this._animate) {
  47153. this._time += this.getScene().getAnimationRatio() * 0.03;
  47154. this.updateShaderUniforms();
  47155. }
  47156. _super.prototype.render.call(this, useCameraPostProcess);
  47157. };
  47158. CustomProceduralTexture.prototype.updateTextures = function () {
  47159. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  47160. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  47161. }
  47162. };
  47163. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  47164. if (this._config) {
  47165. for (var j = 0; j < this._config.uniforms.length; j++) {
  47166. var uniform = this._config.uniforms[j];
  47167. switch (uniform.type) {
  47168. case "float":
  47169. this.setFloat(uniform.name, uniform.value);
  47170. break;
  47171. case "color3":
  47172. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  47173. break;
  47174. case "color4":
  47175. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  47176. break;
  47177. case "vector2":
  47178. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  47179. break;
  47180. case "vector3":
  47181. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  47182. break;
  47183. }
  47184. }
  47185. }
  47186. this.setFloat("time", this._time);
  47187. };
  47188. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  47189. get: function () {
  47190. return this._animate;
  47191. },
  47192. set: function (value) {
  47193. this._animate = value;
  47194. },
  47195. enumerable: true,
  47196. configurable: true
  47197. });
  47198. return CustomProceduralTexture;
  47199. }(BABYLON.ProceduralTexture));
  47200. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  47201. })(BABYLON || (BABYLON = {}));
  47202. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  47203. var BABYLON;
  47204. (function (BABYLON) {
  47205. var FreeCameraGamepadInput = (function () {
  47206. function FreeCameraGamepadInput() {
  47207. this.gamepadAngularSensibility = 200;
  47208. this.gamepadMoveSensibility = 40;
  47209. // private members
  47210. this._cameraTransform = BABYLON.Matrix.Identity();
  47211. this._deltaTransform = BABYLON.Vector3.Zero();
  47212. this._vector3 = BABYLON.Vector3.Zero();
  47213. this._vector2 = BABYLON.Vector2.Zero();
  47214. }
  47215. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  47216. var _this = this;
  47217. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  47218. };
  47219. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  47220. if (this._gamepads) {
  47221. this._gamepads.dispose();
  47222. }
  47223. this.gamepad = null;
  47224. };
  47225. FreeCameraGamepadInput.prototype.checkInputs = function () {
  47226. if (this.gamepad && this.gamepad.leftStick) {
  47227. var camera = this.camera;
  47228. var LSValues = this.gamepad.leftStick;
  47229. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  47230. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  47231. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  47232. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  47233. var RSValues = this.gamepad.rightStick;
  47234. if (RSValues) {
  47235. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  47236. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  47237. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  47238. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  47239. }
  47240. else {
  47241. RSValues = { x: 0, y: 0 };
  47242. }
  47243. if (!camera.rotationQuaternion) {
  47244. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  47245. }
  47246. else {
  47247. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  47248. }
  47249. var speed = camera._computeLocalCameraSpeed() * 50.0;
  47250. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  47251. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  47252. camera.cameraDirection.addInPlace(this._deltaTransform);
  47253. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  47254. camera.cameraRotation.addInPlace(this._vector2);
  47255. }
  47256. };
  47257. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  47258. // Only the first gamepad found can control the camera
  47259. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  47260. // prioritize XBOX gamepads.
  47261. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  47262. this.gamepad = gamepad;
  47263. }
  47264. }
  47265. };
  47266. FreeCameraGamepadInput.prototype.getTypeName = function () {
  47267. return "FreeCameraGamepadInput";
  47268. };
  47269. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  47270. return "gamepad";
  47271. };
  47272. return FreeCameraGamepadInput;
  47273. }());
  47274. __decorate([
  47275. BABYLON.serialize()
  47276. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  47277. __decorate([
  47278. BABYLON.serialize()
  47279. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  47280. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  47281. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  47282. })(BABYLON || (BABYLON = {}));
  47283. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  47284. var BABYLON;
  47285. (function (BABYLON) {
  47286. var ArcRotateCameraGamepadInput = (function () {
  47287. function ArcRotateCameraGamepadInput() {
  47288. this.gamepadRotationSensibility = 80;
  47289. this.gamepadMoveSensibility = 40;
  47290. }
  47291. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  47292. var _this = this;
  47293. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  47294. };
  47295. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  47296. if (this._gamepads) {
  47297. this._gamepads.dispose();
  47298. }
  47299. this.gamepad = null;
  47300. };
  47301. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  47302. if (this.gamepad) {
  47303. var camera = this.camera;
  47304. var RSValues = this.gamepad.rightStick;
  47305. if (RSValues) {
  47306. if (RSValues.x != 0) {
  47307. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  47308. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  47309. camera.inertialAlphaOffset += normalizedRX;
  47310. }
  47311. }
  47312. if (RSValues.y != 0) {
  47313. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  47314. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  47315. camera.inertialBetaOffset += normalizedRY;
  47316. }
  47317. }
  47318. }
  47319. var LSValues = this.gamepad.leftStick;
  47320. if (LSValues && LSValues.y != 0) {
  47321. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  47322. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  47323. this.camera.inertialRadiusOffset -= normalizedLY;
  47324. }
  47325. }
  47326. }
  47327. };
  47328. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  47329. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  47330. // prioritize XBOX gamepads.
  47331. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  47332. this.gamepad = gamepad;
  47333. }
  47334. }
  47335. };
  47336. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  47337. return "ArcRotateCameraGamepadInput";
  47338. };
  47339. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  47340. return "gamepad";
  47341. };
  47342. return ArcRotateCameraGamepadInput;
  47343. }());
  47344. __decorate([
  47345. BABYLON.serialize()
  47346. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  47347. __decorate([
  47348. BABYLON.serialize()
  47349. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  47350. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  47351. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  47352. })(BABYLON || (BABYLON = {}));
  47353. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  47354. var BABYLON;
  47355. (function (BABYLON) {
  47356. var Gamepads = (function () {
  47357. function Gamepads(ongamedpadconnected, ongamedpaddisconnected) {
  47358. var _this = this;
  47359. this.babylonGamepads = [];
  47360. this.oneGamepadConnected = false;
  47361. this.isMonitoring = false;
  47362. this.gamepadEventSupported = 'GamepadEvent' in window;
  47363. this.gamepadSupport = (navigator.getGamepads ||
  47364. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  47365. this._callbackGamepadConnected = ongamedpadconnected;
  47366. this._callbackGamepadDisconnected = ongamedpaddisconnected;
  47367. if (this.gamepadSupport) {
  47368. //first add already-connected gamepads
  47369. this._updateGamepadObjects();
  47370. if (this.babylonGamepads.length) {
  47371. this._startMonitoringGamepads();
  47372. }
  47373. // Checking if the gamepad connected event is supported (like in Firefox)
  47374. if (this.gamepadEventSupported) {
  47375. this._onGamepadConnectedEvent = function (evt) {
  47376. _this._onGamepadConnected(evt.gamepad);
  47377. };
  47378. this._onGamepadDisonnectedEvent = function (evt) {
  47379. _this._onGamepadDisconnected(evt.gamepad);
  47380. };
  47381. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  47382. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  47383. }
  47384. else {
  47385. this._startMonitoringGamepads();
  47386. }
  47387. }
  47388. }
  47389. Gamepads.prototype.dispose = function () {
  47390. if (this._onGamepadConnectedEvent) {
  47391. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  47392. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  47393. this._onGamepadConnectedEvent = null;
  47394. this._onGamepadDisonnectedEvent = null;
  47395. }
  47396. this.oneGamepadConnected = false;
  47397. this._stopMonitoringGamepads();
  47398. this.babylonGamepads = [];
  47399. };
  47400. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  47401. // Protection code for Chrome which has a very buggy gamepad implementation...
  47402. // And raises a connected event on disconnection for instance
  47403. if (gamepad.index in this.babylonGamepads) {
  47404. return;
  47405. }
  47406. var newGamepad = this._addNewGamepad(gamepad);
  47407. if (this._callbackGamepadConnected)
  47408. this._callbackGamepadConnected(newGamepad);
  47409. this._startMonitoringGamepads();
  47410. };
  47411. Gamepads.prototype._addNewGamepad = function (gamepad) {
  47412. if (!this.oneGamepadConnected) {
  47413. this.oneGamepadConnected = true;
  47414. }
  47415. var newGamepad;
  47416. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  47417. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  47418. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  47419. }
  47420. else if (gamepad.pose) {
  47421. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  47422. }
  47423. else {
  47424. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  47425. }
  47426. this.babylonGamepads.push(newGamepad);
  47427. return newGamepad;
  47428. };
  47429. Gamepads.prototype._onGamepadDisconnected = function (gamepad) {
  47430. // Remove the gamepad from the list of gamepads to monitor.
  47431. for (var i in this.babylonGamepads) {
  47432. if (this.babylonGamepads[i].index == gamepad.index) {
  47433. this.babylonGamepads.splice(+i, 1);
  47434. break;
  47435. }
  47436. }
  47437. // If no gamepads are left, stop the polling loop.
  47438. if (this.babylonGamepads.length == 0) {
  47439. this._stopMonitoringGamepads();
  47440. this.oneGamepadConnected = false;
  47441. }
  47442. if (this._callbackGamepadDisconnected)
  47443. this._callbackGamepadDisconnected(gamepad);
  47444. };
  47445. Gamepads.prototype._startMonitoringGamepads = function () {
  47446. if (!this.isMonitoring) {
  47447. this.isMonitoring = true;
  47448. this._checkGamepadsStatus();
  47449. }
  47450. };
  47451. Gamepads.prototype._stopMonitoringGamepads = function () {
  47452. this.isMonitoring = false;
  47453. };
  47454. Gamepads.prototype._checkGamepadsStatus = function () {
  47455. var _this = this;
  47456. // Hack to be compatible Chrome
  47457. this._updateGamepadObjects();
  47458. for (var i in this.babylonGamepads) {
  47459. this.babylonGamepads[i].update();
  47460. }
  47461. if (this.isMonitoring) {
  47462. if (window.requestAnimationFrame) {
  47463. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47464. }
  47465. else if (window.mozRequestAnimationFrame) {
  47466. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47467. }
  47468. else if (window.webkitRequestAnimationFrame) {
  47469. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47470. }
  47471. }
  47472. };
  47473. // This function is called only on Chrome, which does not properly support
  47474. // connection/disconnection events and forces you to recopy again the gamepad object
  47475. Gamepads.prototype._updateGamepadObjects = function () {
  47476. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  47477. for (var i = 0; i < gamepads.length; i++) {
  47478. if (gamepads[i]) {
  47479. if (!(gamepads[i].index in this.babylonGamepads)) {
  47480. var newGamepad = this._addNewGamepad(gamepads[i]);
  47481. if (this._callbackGamepadConnected) {
  47482. this._callbackGamepadConnected(newGamepad);
  47483. }
  47484. }
  47485. else {
  47486. // Forced to copy again this object for Chrome for unknown reason
  47487. this.babylonGamepads[i].browserGamepad = gamepads[i];
  47488. }
  47489. }
  47490. }
  47491. };
  47492. return Gamepads;
  47493. }());
  47494. BABYLON.Gamepads = Gamepads;
  47495. var StickValues = (function () {
  47496. function StickValues(x, y) {
  47497. this.x = x;
  47498. this.y = y;
  47499. }
  47500. return StickValues;
  47501. }());
  47502. BABYLON.StickValues = StickValues;
  47503. var Gamepad = (function () {
  47504. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  47505. if (leftStickX === void 0) { leftStickX = 0; }
  47506. if (leftStickY === void 0) { leftStickY = 1; }
  47507. if (rightStickX === void 0) { rightStickX = 2; }
  47508. if (rightStickY === void 0) { rightStickY = 3; }
  47509. this.id = id;
  47510. this.index = index;
  47511. this.browserGamepad = browserGamepad;
  47512. this.type = Gamepad.GAMEPAD;
  47513. this._leftStickAxisX = leftStickX;
  47514. this._leftStickAxisY = leftStickY;
  47515. this._rightStickAxisX = rightStickX;
  47516. this._rightStickAxisY = rightStickY;
  47517. if (this.browserGamepad.axes.length >= 2) {
  47518. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47519. }
  47520. if (this.browserGamepad.axes.length >= 4) {
  47521. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47522. }
  47523. }
  47524. Gamepad.prototype.onleftstickchanged = function (callback) {
  47525. this._onleftstickchanged = callback;
  47526. };
  47527. Gamepad.prototype.onrightstickchanged = function (callback) {
  47528. this._onrightstickchanged = callback;
  47529. };
  47530. Object.defineProperty(Gamepad.prototype, "leftStick", {
  47531. get: function () {
  47532. return this._leftStick;
  47533. },
  47534. set: function (newValues) {
  47535. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  47536. this._onleftstickchanged(newValues);
  47537. }
  47538. this._leftStick = newValues;
  47539. },
  47540. enumerable: true,
  47541. configurable: true
  47542. });
  47543. Object.defineProperty(Gamepad.prototype, "rightStick", {
  47544. get: function () {
  47545. return this._rightStick;
  47546. },
  47547. set: function (newValues) {
  47548. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  47549. this._onrightstickchanged(newValues);
  47550. }
  47551. this._rightStick = newValues;
  47552. },
  47553. enumerable: true,
  47554. configurable: true
  47555. });
  47556. Gamepad.prototype.update = function () {
  47557. if (this._leftStick) {
  47558. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47559. }
  47560. if (this._rightStick) {
  47561. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47562. }
  47563. };
  47564. return Gamepad;
  47565. }());
  47566. Gamepad.GAMEPAD = 0;
  47567. Gamepad.GENERIC = 1;
  47568. Gamepad.XBOX = 2;
  47569. Gamepad.POSE_ENABLED = 3;
  47570. BABYLON.Gamepad = Gamepad;
  47571. var GenericPad = (function (_super) {
  47572. __extends(GenericPad, _super);
  47573. function GenericPad(id, index, browserGamepad) {
  47574. var _this = _super.call(this, id, index, browserGamepad) || this;
  47575. _this.type = Gamepad.GENERIC;
  47576. _this._buttons = new Array(browserGamepad.buttons.length);
  47577. return _this;
  47578. }
  47579. GenericPad.prototype.onbuttondown = function (callback) {
  47580. this._onbuttondown = callback;
  47581. };
  47582. GenericPad.prototype.onbuttonup = function (callback) {
  47583. this._onbuttonup = callback;
  47584. };
  47585. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  47586. if (newValue !== currentValue) {
  47587. if (this._onbuttondown && newValue === 1) {
  47588. this._onbuttondown(buttonIndex);
  47589. }
  47590. if (this._onbuttonup && newValue === 0) {
  47591. this._onbuttonup(buttonIndex);
  47592. }
  47593. }
  47594. return newValue;
  47595. };
  47596. GenericPad.prototype.update = function () {
  47597. _super.prototype.update.call(this);
  47598. for (var index = 0; index < this._buttons.length; index++) {
  47599. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  47600. }
  47601. };
  47602. return GenericPad;
  47603. }(Gamepad));
  47604. BABYLON.GenericPad = GenericPad;
  47605. var Xbox360Button;
  47606. (function (Xbox360Button) {
  47607. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  47608. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  47609. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  47610. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  47611. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  47612. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  47613. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  47614. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  47615. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  47616. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  47617. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  47618. var Xbox360Dpad;
  47619. (function (Xbox360Dpad) {
  47620. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  47621. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  47622. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  47623. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  47624. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  47625. var Xbox360Pad = (function (_super) {
  47626. __extends(Xbox360Pad, _super);
  47627. function Xbox360Pad(id, index, gamepad, xboxOne) {
  47628. if (xboxOne === void 0) { xboxOne = false; }
  47629. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  47630. _this._leftTrigger = 0;
  47631. _this._rightTrigger = 0;
  47632. _this._buttonA = 0;
  47633. _this._buttonB = 0;
  47634. _this._buttonX = 0;
  47635. _this._buttonY = 0;
  47636. _this._buttonBack = 0;
  47637. _this._buttonStart = 0;
  47638. _this._buttonLB = 0;
  47639. _this._buttonRB = 0;
  47640. _this._buttonLeftStick = 0;
  47641. _this._buttonRightStick = 0;
  47642. _this._dPadUp = 0;
  47643. _this._dPadDown = 0;
  47644. _this._dPadLeft = 0;
  47645. _this._dPadRight = 0;
  47646. _this._isXboxOnePad = false;
  47647. _this.type = Gamepad.XBOX;
  47648. _this._isXboxOnePad = xboxOne;
  47649. return _this;
  47650. }
  47651. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  47652. this._onlefttriggerchanged = callback;
  47653. };
  47654. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  47655. this._onrighttriggerchanged = callback;
  47656. };
  47657. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  47658. get: function () {
  47659. return this._leftTrigger;
  47660. },
  47661. set: function (newValue) {
  47662. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  47663. this._onlefttriggerchanged(newValue);
  47664. }
  47665. this._leftTrigger = newValue;
  47666. },
  47667. enumerable: true,
  47668. configurable: true
  47669. });
  47670. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  47671. get: function () {
  47672. return this._rightTrigger;
  47673. },
  47674. set: function (newValue) {
  47675. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  47676. this._onrighttriggerchanged(newValue);
  47677. }
  47678. this._rightTrigger = newValue;
  47679. },
  47680. enumerable: true,
  47681. configurable: true
  47682. });
  47683. Xbox360Pad.prototype.onbuttondown = function (callback) {
  47684. this._onbuttondown = callback;
  47685. };
  47686. Xbox360Pad.prototype.onbuttonup = function (callback) {
  47687. this._onbuttonup = callback;
  47688. };
  47689. Xbox360Pad.prototype.ondpaddown = function (callback) {
  47690. this._ondpaddown = callback;
  47691. };
  47692. Xbox360Pad.prototype.ondpadup = function (callback) {
  47693. this._ondpadup = callback;
  47694. };
  47695. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  47696. if (newValue !== currentValue) {
  47697. if (this._onbuttondown && newValue === 1) {
  47698. this._onbuttondown(buttonType);
  47699. }
  47700. if (this._onbuttonup && newValue === 0) {
  47701. this._onbuttonup(buttonType);
  47702. }
  47703. }
  47704. return newValue;
  47705. };
  47706. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  47707. if (newValue !== currentValue) {
  47708. if (this._ondpaddown && newValue === 1) {
  47709. this._ondpaddown(buttonType);
  47710. }
  47711. if (this._ondpadup && newValue === 0) {
  47712. this._ondpadup(buttonType);
  47713. }
  47714. }
  47715. return newValue;
  47716. };
  47717. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  47718. get: function () {
  47719. return this._buttonA;
  47720. },
  47721. set: function (value) {
  47722. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  47723. },
  47724. enumerable: true,
  47725. configurable: true
  47726. });
  47727. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  47728. get: function () {
  47729. return this._buttonB;
  47730. },
  47731. set: function (value) {
  47732. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  47733. },
  47734. enumerable: true,
  47735. configurable: true
  47736. });
  47737. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  47738. get: function () {
  47739. return this._buttonX;
  47740. },
  47741. set: function (value) {
  47742. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  47743. },
  47744. enumerable: true,
  47745. configurable: true
  47746. });
  47747. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  47748. get: function () {
  47749. return this._buttonY;
  47750. },
  47751. set: function (value) {
  47752. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  47753. },
  47754. enumerable: true,
  47755. configurable: true
  47756. });
  47757. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  47758. get: function () {
  47759. return this._buttonStart;
  47760. },
  47761. set: function (value) {
  47762. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  47763. },
  47764. enumerable: true,
  47765. configurable: true
  47766. });
  47767. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  47768. get: function () {
  47769. return this._buttonBack;
  47770. },
  47771. set: function (value) {
  47772. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  47773. },
  47774. enumerable: true,
  47775. configurable: true
  47776. });
  47777. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  47778. get: function () {
  47779. return this._buttonLB;
  47780. },
  47781. set: function (value) {
  47782. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  47783. },
  47784. enumerable: true,
  47785. configurable: true
  47786. });
  47787. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  47788. get: function () {
  47789. return this._buttonRB;
  47790. },
  47791. set: function (value) {
  47792. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  47793. },
  47794. enumerable: true,
  47795. configurable: true
  47796. });
  47797. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  47798. get: function () {
  47799. return this._buttonLeftStick;
  47800. },
  47801. set: function (value) {
  47802. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  47803. },
  47804. enumerable: true,
  47805. configurable: true
  47806. });
  47807. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  47808. get: function () {
  47809. return this._buttonRightStick;
  47810. },
  47811. set: function (value) {
  47812. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  47813. },
  47814. enumerable: true,
  47815. configurable: true
  47816. });
  47817. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  47818. get: function () {
  47819. return this._dPadUp;
  47820. },
  47821. set: function (value) {
  47822. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  47823. },
  47824. enumerable: true,
  47825. configurable: true
  47826. });
  47827. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  47828. get: function () {
  47829. return this._dPadDown;
  47830. },
  47831. set: function (value) {
  47832. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  47833. },
  47834. enumerable: true,
  47835. configurable: true
  47836. });
  47837. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  47838. get: function () {
  47839. return this._dPadLeft;
  47840. },
  47841. set: function (value) {
  47842. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  47843. },
  47844. enumerable: true,
  47845. configurable: true
  47846. });
  47847. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  47848. get: function () {
  47849. return this._dPadRight;
  47850. },
  47851. set: function (value) {
  47852. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  47853. },
  47854. enumerable: true,
  47855. configurable: true
  47856. });
  47857. Xbox360Pad.prototype.update = function () {
  47858. _super.prototype.update.call(this);
  47859. if (this._isXboxOnePad) {
  47860. this.buttonA = this.browserGamepad.buttons[0].value;
  47861. this.buttonB = this.browserGamepad.buttons[1].value;
  47862. this.buttonX = this.browserGamepad.buttons[2].value;
  47863. this.buttonY = this.browserGamepad.buttons[3].value;
  47864. this.buttonLB = this.browserGamepad.buttons[4].value;
  47865. this.buttonRB = this.browserGamepad.buttons[5].value;
  47866. this.leftTrigger = this.browserGamepad.axes[2];
  47867. this.rightTrigger = this.browserGamepad.axes[5];
  47868. this.buttonBack = this.browserGamepad.buttons[9].value;
  47869. this.buttonStart = this.browserGamepad.buttons[8].value;
  47870. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  47871. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  47872. this.dPadUp = this.browserGamepad.buttons[11].value;
  47873. this.dPadDown = this.browserGamepad.buttons[12].value;
  47874. this.dPadLeft = this.browserGamepad.buttons[13].value;
  47875. this.dPadRight = this.browserGamepad.buttons[14].value;
  47876. }
  47877. else {
  47878. this.buttonA = this.browserGamepad.buttons[0].value;
  47879. this.buttonB = this.browserGamepad.buttons[1].value;
  47880. this.buttonX = this.browserGamepad.buttons[2].value;
  47881. this.buttonY = this.browserGamepad.buttons[3].value;
  47882. this.buttonLB = this.browserGamepad.buttons[4].value;
  47883. this.buttonRB = this.browserGamepad.buttons[5].value;
  47884. this.leftTrigger = this.browserGamepad.buttons[6].value;
  47885. this.rightTrigger = this.browserGamepad.buttons[7].value;
  47886. this.buttonBack = this.browserGamepad.buttons[8].value;
  47887. this.buttonStart = this.browserGamepad.buttons[9].value;
  47888. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  47889. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  47890. this.dPadUp = this.browserGamepad.buttons[12].value;
  47891. this.dPadDown = this.browserGamepad.buttons[13].value;
  47892. this.dPadLeft = this.browserGamepad.buttons[14].value;
  47893. this.dPadRight = this.browserGamepad.buttons[15].value;
  47894. }
  47895. };
  47896. return Xbox360Pad;
  47897. }(Gamepad));
  47898. BABYLON.Xbox360Pad = Xbox360Pad;
  47899. })(BABYLON || (BABYLON = {}));
  47900. //# sourceMappingURL=babylon.gamepads.js.map
  47901. var BABYLON;
  47902. (function (BABYLON) {
  47903. var PoseEnabledControllerType;
  47904. (function (PoseEnabledControllerType) {
  47905. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  47906. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  47907. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  47908. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  47909. var PoseEnabledControllerHelper = (function () {
  47910. function PoseEnabledControllerHelper() {
  47911. }
  47912. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  47913. // for now, only Oculus and Vive are supported
  47914. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  47915. return new OculusTouchController(vrGamepad);
  47916. }
  47917. else {
  47918. return new ViveController(vrGamepad);
  47919. }
  47920. };
  47921. return PoseEnabledControllerHelper;
  47922. }());
  47923. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  47924. var PoseEnabledController = (function (_super) {
  47925. __extends(PoseEnabledController, _super);
  47926. function PoseEnabledController(vrGamepad) {
  47927. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  47928. _this.vrGamepad = vrGamepad;
  47929. _this.deviceScaleFactor = 1;
  47930. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  47931. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  47932. _this.controllerType = PoseEnabledControllerType.GENERIC;
  47933. _this.position = BABYLON.Vector3.Zero();
  47934. _this.rotationQuaternion = new BABYLON.Quaternion();
  47935. _this.devicePosition = BABYLON.Vector3.Zero();
  47936. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  47937. _this._calculatedPosition = BABYLON.Vector3.Zero();
  47938. _this._calculatedRotation = new BABYLON.Quaternion();
  47939. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  47940. return _this;
  47941. }
  47942. PoseEnabledController.prototype.update = function () {
  47943. _super.prototype.update.call(this);
  47944. var pose = this.vrGamepad.pose;
  47945. this.updateFromDevice(pose);
  47946. if (this._mesh) {
  47947. this._mesh.position.copyFrom(this._calculatedPosition);
  47948. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  47949. }
  47950. };
  47951. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  47952. if (poseData) {
  47953. this.rawPose = poseData;
  47954. if (poseData.position) {
  47955. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  47956. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  47957. this.devicePosition.z *= -1;
  47958. }
  47959. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  47960. this._calculatedPosition.addInPlace(this.position);
  47961. }
  47962. if (poseData.orientation) {
  47963. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  47964. if (this._mesh) {
  47965. if (this._mesh.getScene().useRightHandedSystem) {
  47966. this.deviceRotationQuaternion.z *= -1;
  47967. this.deviceRotationQuaternion.w *= -1;
  47968. }
  47969. else {
  47970. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  47971. }
  47972. }
  47973. // if the camera is set, rotate to the camera's rotation
  47974. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  47975. }
  47976. }
  47977. };
  47978. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  47979. if (this._mesh) {
  47980. this._mesh.parent = undefined;
  47981. }
  47982. this._mesh = mesh;
  47983. if (this._poseControlledCamera) {
  47984. this._mesh.parent = this._poseControlledCamera;
  47985. }
  47986. if (!this._mesh.rotationQuaternion) {
  47987. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  47988. }
  47989. };
  47990. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  47991. this._poseControlledCamera = camera;
  47992. if (this._mesh) {
  47993. this._mesh.parent = this._poseControlledCamera;
  47994. }
  47995. };
  47996. PoseEnabledController.prototype.detachMesh = function () {
  47997. this._mesh = undefined;
  47998. };
  47999. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  48000. get: function () {
  48001. return this._mesh;
  48002. },
  48003. enumerable: true,
  48004. configurable: true
  48005. });
  48006. PoseEnabledController.prototype.getForwardRay = function (length) {
  48007. if (length === void 0) { length = 100; }
  48008. if (!this.mesh) {
  48009. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  48010. }
  48011. var m = this.mesh.getWorldMatrix();
  48012. var origin = m.getTranslation();
  48013. var forward = new BABYLON.Vector3(0, 0, -1);
  48014. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  48015. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  48016. return new BABYLON.Ray(origin, direction, length);
  48017. };
  48018. return PoseEnabledController;
  48019. }(BABYLON.Gamepad));
  48020. BABYLON.PoseEnabledController = PoseEnabledController;
  48021. var WebVRController = (function (_super) {
  48022. __extends(WebVRController, _super);
  48023. function WebVRController(vrGamepad) {
  48024. var _this = _super.call(this, vrGamepad) || this;
  48025. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  48026. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  48027. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  48028. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  48029. _this.onPadStateChangedObservable = new BABYLON.Observable();
  48030. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  48031. _this.pad = { x: 0, y: 0 };
  48032. // avoid GC, store state in a tmp object
  48033. _this._changes = {
  48034. pressChanged: false,
  48035. touchChanged: false,
  48036. valueChanged: false,
  48037. changed: false
  48038. };
  48039. _this._buttons = new Array(vrGamepad.buttons.length);
  48040. _this.hand = vrGamepad.hand;
  48041. return _this;
  48042. }
  48043. WebVRController.prototype.onButtonStateChange = function (callback) {
  48044. this._onButtonStateChange = callback;
  48045. };
  48046. WebVRController.prototype.update = function () {
  48047. _super.prototype.update.call(this);
  48048. for (var index = 0; index < this._buttons.length; index++) {
  48049. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  48050. }
  48051. ;
  48052. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  48053. this.pad.x = this.leftStick.x;
  48054. this.pad.y = this.leftStick.y;
  48055. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  48056. }
  48057. };
  48058. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  48059. if (!currentState) {
  48060. this._buttons[buttonIndex] = {
  48061. pressed: newState.pressed,
  48062. touched: newState.touched,
  48063. value: newState.value
  48064. };
  48065. return;
  48066. }
  48067. this._checkChanges(newState, currentState);
  48068. if (this._changes.changed) {
  48069. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  48070. this.handleButtonChange(buttonIndex, newState, this._changes);
  48071. }
  48072. this._buttons[buttonIndex].pressed = newState.pressed;
  48073. this._buttons[buttonIndex].touched = newState.touched;
  48074. // oculus triggers are never 0, thou not touched.
  48075. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  48076. };
  48077. WebVRController.prototype._checkChanges = function (newState, currentState) {
  48078. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  48079. this._changes.touchChanged = newState.touched !== currentState.touched;
  48080. this._changes.valueChanged = newState.value !== currentState.value;
  48081. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  48082. return this._changes;
  48083. };
  48084. return WebVRController;
  48085. }(PoseEnabledController));
  48086. BABYLON.WebVRController = WebVRController;
  48087. var OculusTouchController = (function (_super) {
  48088. __extends(OculusTouchController, _super);
  48089. function OculusTouchController(vrGamepad) {
  48090. var _this = _super.call(this, vrGamepad) || this;
  48091. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  48092. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  48093. _this.controllerType = PoseEnabledControllerType.OCULUS;
  48094. return _this;
  48095. }
  48096. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  48097. var _this = this;
  48098. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  48099. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  48100. /*
  48101. Parent Mesh name: oculus_touch_left
  48102. - body
  48103. - trigger
  48104. - thumbstick
  48105. - grip
  48106. - button_y
  48107. - button_x
  48108. - button_enter
  48109. */
  48110. _this._defaultModel = newMeshes[1];
  48111. if (meshLoaded) {
  48112. meshLoaded(_this._defaultModel);
  48113. }
  48114. _this.attachToMesh(_this._defaultModel);
  48115. });
  48116. };
  48117. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  48118. // helper getters for left and right hand.
  48119. get: function () {
  48120. if (this.hand === 'right') {
  48121. return this.onMainButtonStateChangedObservable;
  48122. }
  48123. else {
  48124. throw new Error('No A button on left hand');
  48125. }
  48126. },
  48127. enumerable: true,
  48128. configurable: true
  48129. });
  48130. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  48131. get: function () {
  48132. if (this.hand === 'right') {
  48133. return this.onSecondaryButtonStateChangedObservable;
  48134. }
  48135. else {
  48136. throw new Error('No B button on left hand');
  48137. }
  48138. },
  48139. enumerable: true,
  48140. configurable: true
  48141. });
  48142. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  48143. get: function () {
  48144. if (this.hand === 'left') {
  48145. return this.onMainButtonStateChangedObservable;
  48146. }
  48147. else {
  48148. throw new Error('No X button on right hand');
  48149. }
  48150. },
  48151. enumerable: true,
  48152. configurable: true
  48153. });
  48154. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  48155. get: function () {
  48156. if (this.hand === 'left') {
  48157. return this.onSecondaryButtonStateChangedObservable;
  48158. }
  48159. else {
  48160. throw new Error('No Y button on right hand');
  48161. }
  48162. },
  48163. enumerable: true,
  48164. configurable: true
  48165. });
  48166. /*
  48167. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  48168. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  48169. 2) secondary trigger (same)
  48170. 3) A (right) X (left), touch, pressed = value
  48171. 4) B / Y
  48172. 5) thumb rest
  48173. */
  48174. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  48175. var notifyObject = state; //{ state: state, changes: changes };
  48176. var triggerDirection = this.hand === 'right' ? -1 : 1;
  48177. switch (buttonIdx) {
  48178. case 0:
  48179. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  48180. return;
  48181. case 1:
  48182. if (this._defaultModel) {
  48183. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  48184. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  48185. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  48186. }
  48187. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  48188. return;
  48189. case 2:
  48190. if (this._defaultModel) {
  48191. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  48192. }
  48193. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  48194. return;
  48195. case 3:
  48196. if (this._defaultModel) {
  48197. if (notifyObject.pressed) {
  48198. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  48199. }
  48200. else {
  48201. (this._defaultModel.getChildren()[1]).position.y = 0;
  48202. }
  48203. }
  48204. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  48205. return;
  48206. case 4:
  48207. if (this._defaultModel) {
  48208. if (notifyObject.pressed) {
  48209. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  48210. }
  48211. else {
  48212. (this._defaultModel.getChildren()[2]).position.y = 0;
  48213. }
  48214. }
  48215. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  48216. return;
  48217. case 5:
  48218. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  48219. return;
  48220. }
  48221. };
  48222. return OculusTouchController;
  48223. }(WebVRController));
  48224. BABYLON.OculusTouchController = OculusTouchController;
  48225. var ViveController = (function (_super) {
  48226. __extends(ViveController, _super);
  48227. function ViveController(vrGamepad) {
  48228. var _this = _super.call(this, vrGamepad) || this;
  48229. _this.controllerType = PoseEnabledControllerType.VIVE;
  48230. return _this;
  48231. }
  48232. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  48233. var _this = this;
  48234. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  48235. /*
  48236. Parent Mesh name: ViveWand
  48237. - body
  48238. - r_gripper
  48239. - l_gripper
  48240. - menu_button
  48241. - system_button
  48242. - trackpad
  48243. - trigger
  48244. - LED
  48245. */
  48246. _this._defaultModel = newMeshes[1];
  48247. if (meshLoaded) {
  48248. meshLoaded(_this._defaultModel);
  48249. }
  48250. _this.attachToMesh(_this._defaultModel);
  48251. });
  48252. };
  48253. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  48254. get: function () {
  48255. return this.onMainButtonStateChangedObservable;
  48256. },
  48257. enumerable: true,
  48258. configurable: true
  48259. });
  48260. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  48261. get: function () {
  48262. return this.onMainButtonStateChangedObservable;
  48263. },
  48264. enumerable: true,
  48265. configurable: true
  48266. });
  48267. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  48268. get: function () {
  48269. return this.onSecondaryButtonStateChangedObservable;
  48270. },
  48271. enumerable: true,
  48272. configurable: true
  48273. });
  48274. /**
  48275. * Vive mapping:
  48276. * 0: touchpad
  48277. * 1: trigger
  48278. * 2: left AND right buttons
  48279. * 3: menu button
  48280. */
  48281. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  48282. var notifyObject = state; //{ state: state, changes: changes };
  48283. switch (buttonIdx) {
  48284. case 0:
  48285. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  48286. return;
  48287. case 1:
  48288. if (this._defaultModel) {
  48289. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  48290. }
  48291. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  48292. return;
  48293. case 2:
  48294. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  48295. return;
  48296. case 3:
  48297. if (this._defaultModel) {
  48298. if (notifyObject.pressed) {
  48299. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  48300. }
  48301. else {
  48302. (this._defaultModel.getChildren()[2]).position.y = 0;
  48303. }
  48304. }
  48305. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  48306. return;
  48307. }
  48308. };
  48309. return ViveController;
  48310. }(WebVRController));
  48311. BABYLON.ViveController = ViveController;
  48312. })(BABYLON || (BABYLON = {}));
  48313. //# sourceMappingURL=babylon.extendedGamepad.js.map
  48314. /// <reference path="babylon.targetCamera.ts" />
  48315. var BABYLON;
  48316. (function (BABYLON) {
  48317. var FollowCamera = (function (_super) {
  48318. __extends(FollowCamera, _super);
  48319. function FollowCamera(name, position, scene, lockedTarget) {
  48320. var _this = _super.call(this, name, position, scene) || this;
  48321. _this.radius = 12;
  48322. _this.rotationOffset = 0;
  48323. _this.heightOffset = 4;
  48324. _this.cameraAcceleration = 0.05;
  48325. _this.maxCameraSpeed = 20;
  48326. _this.lockedTarget = lockedTarget;
  48327. return _this;
  48328. }
  48329. FollowCamera.prototype.getRadians = function (degrees) {
  48330. return degrees * Math.PI / 180;
  48331. };
  48332. FollowCamera.prototype.follow = function (cameraTarget) {
  48333. if (!cameraTarget)
  48334. return;
  48335. var yRotation;
  48336. if (cameraTarget.rotationQuaternion) {
  48337. var rotMatrix = new BABYLON.Matrix();
  48338. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  48339. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  48340. }
  48341. else {
  48342. yRotation = cameraTarget.rotation.y;
  48343. }
  48344. var radians = this.getRadians(this.rotationOffset) + yRotation;
  48345. var targetPosition = cameraTarget.getAbsolutePosition();
  48346. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  48347. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  48348. var dx = targetX - this.position.x;
  48349. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  48350. var dz = (targetZ) - this.position.z;
  48351. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  48352. var vy = dy * this.cameraAcceleration;
  48353. var vz = dz * this.cameraAcceleration * 2;
  48354. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  48355. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  48356. }
  48357. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  48358. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  48359. }
  48360. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  48361. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  48362. }
  48363. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  48364. this.setTarget(targetPosition);
  48365. };
  48366. FollowCamera.prototype._checkInputs = function () {
  48367. _super.prototype._checkInputs.call(this);
  48368. this.follow(this.lockedTarget);
  48369. };
  48370. FollowCamera.prototype.getClassName = function () {
  48371. return "FollowCamera";
  48372. };
  48373. return FollowCamera;
  48374. }(BABYLON.TargetCamera));
  48375. __decorate([
  48376. BABYLON.serialize()
  48377. ], FollowCamera.prototype, "radius", void 0);
  48378. __decorate([
  48379. BABYLON.serialize()
  48380. ], FollowCamera.prototype, "rotationOffset", void 0);
  48381. __decorate([
  48382. BABYLON.serialize()
  48383. ], FollowCamera.prototype, "heightOffset", void 0);
  48384. __decorate([
  48385. BABYLON.serialize()
  48386. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  48387. __decorate([
  48388. BABYLON.serialize()
  48389. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  48390. __decorate([
  48391. BABYLON.serializeAsMeshReference("lockedTargetId")
  48392. ], FollowCamera.prototype, "lockedTarget", void 0);
  48393. BABYLON.FollowCamera = FollowCamera;
  48394. var ArcFollowCamera = (function (_super) {
  48395. __extends(ArcFollowCamera, _super);
  48396. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  48397. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  48398. _this.alpha = alpha;
  48399. _this.beta = beta;
  48400. _this.radius = radius;
  48401. _this.target = target;
  48402. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  48403. _this.follow();
  48404. return _this;
  48405. }
  48406. ArcFollowCamera.prototype.follow = function () {
  48407. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  48408. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  48409. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  48410. var targetPosition = this.target.getAbsolutePosition();
  48411. this.position = targetPosition.add(this._cartesianCoordinates);
  48412. this.setTarget(targetPosition);
  48413. };
  48414. ArcFollowCamera.prototype._checkInputs = function () {
  48415. _super.prototype._checkInputs.call(this);
  48416. this.follow();
  48417. };
  48418. ArcFollowCamera.prototype.getClassName = function () {
  48419. return "ArcFollowCamera";
  48420. };
  48421. return ArcFollowCamera;
  48422. }(BABYLON.TargetCamera));
  48423. BABYLON.ArcFollowCamera = ArcFollowCamera;
  48424. })(BABYLON || (BABYLON = {}));
  48425. //# sourceMappingURL=babylon.followCamera.js.map
  48426. /// <reference path="babylon.touchCamera.ts" />
  48427. var BABYLON;
  48428. (function (BABYLON) {
  48429. // We're mainly based on the logic defined into the FreeCamera code
  48430. var UniversalCamera = (function (_super) {
  48431. __extends(UniversalCamera, _super);
  48432. //-- end properties for backward compatibility for inputs
  48433. function UniversalCamera(name, position, scene) {
  48434. var _this = _super.call(this, name, position, scene) || this;
  48435. _this.inputs.addGamepad();
  48436. return _this;
  48437. }
  48438. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  48439. //-- Begin properties for backward compatibility for inputs
  48440. get: function () {
  48441. var gamepad = this.inputs.attached["gamepad"];
  48442. if (gamepad)
  48443. return gamepad.gamepadAngularSensibility;
  48444. },
  48445. set: function (value) {
  48446. var gamepad = this.inputs.attached["gamepad"];
  48447. if (gamepad)
  48448. gamepad.gamepadAngularSensibility = value;
  48449. },
  48450. enumerable: true,
  48451. configurable: true
  48452. });
  48453. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  48454. get: function () {
  48455. var gamepad = this.inputs.attached["gamepad"];
  48456. if (gamepad)
  48457. return gamepad.gamepadMoveSensibility;
  48458. },
  48459. set: function (value) {
  48460. var gamepad = this.inputs.attached["gamepad"];
  48461. if (gamepad)
  48462. gamepad.gamepadMoveSensibility = value;
  48463. },
  48464. enumerable: true,
  48465. configurable: true
  48466. });
  48467. UniversalCamera.prototype.getClassName = function () {
  48468. return "UniversalCamera";
  48469. };
  48470. return UniversalCamera;
  48471. }(BABYLON.TouchCamera));
  48472. BABYLON.UniversalCamera = UniversalCamera;
  48473. })(BABYLON || (BABYLON = {}));
  48474. //# sourceMappingURL=babylon.universalCamera.js.map
  48475. /// <reference path="babylon.universalCamera.ts" />
  48476. var BABYLON;
  48477. (function (BABYLON) {
  48478. // We're mainly based on the logic defined into the FreeCamera code
  48479. var GamepadCamera = (function (_super) {
  48480. __extends(GamepadCamera, _super);
  48481. //-- end properties for backward compatibility for inputs
  48482. function GamepadCamera(name, position, scene) {
  48483. return _super.call(this, name, position, scene) || this;
  48484. }
  48485. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  48486. //-- Begin properties for backward compatibility for inputs
  48487. get: function () {
  48488. var gamepad = this.inputs.attached["gamepad"];
  48489. if (gamepad)
  48490. return gamepad.gamepadAngularSensibility;
  48491. },
  48492. set: function (value) {
  48493. var gamepad = this.inputs.attached["gamepad"];
  48494. if (gamepad)
  48495. gamepad.gamepadAngularSensibility = value;
  48496. },
  48497. enumerable: true,
  48498. configurable: true
  48499. });
  48500. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  48501. get: function () {
  48502. var gamepad = this.inputs.attached["gamepad"];
  48503. if (gamepad)
  48504. return gamepad.gamepadMoveSensibility;
  48505. },
  48506. set: function (value) {
  48507. var gamepad = this.inputs.attached["gamepad"];
  48508. if (gamepad)
  48509. gamepad.gamepadMoveSensibility = value;
  48510. },
  48511. enumerable: true,
  48512. configurable: true
  48513. });
  48514. GamepadCamera.prototype.getClassName = function () {
  48515. return "GamepadCamera";
  48516. };
  48517. return GamepadCamera;
  48518. }(BABYLON.UniversalCamera));
  48519. BABYLON.GamepadCamera = GamepadCamera;
  48520. })(BABYLON || (BABYLON = {}));
  48521. //# sourceMappingURL=babylon.gamepadCamera.js.map
  48522. var BABYLON;
  48523. (function (BABYLON) {
  48524. var PostProcessRenderPipelineManager = (function () {
  48525. function PostProcessRenderPipelineManager() {
  48526. this._renderPipelines = {};
  48527. }
  48528. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  48529. this._renderPipelines[renderPipeline._name] = renderPipeline;
  48530. };
  48531. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  48532. var renderPipeline = this._renderPipelines[renderPipelineName];
  48533. if (!renderPipeline) {
  48534. return;
  48535. }
  48536. renderPipeline._attachCameras(cameras, unique);
  48537. };
  48538. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  48539. var renderPipeline = this._renderPipelines[renderPipelineName];
  48540. if (!renderPipeline) {
  48541. return;
  48542. }
  48543. renderPipeline._detachCameras(cameras);
  48544. };
  48545. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  48546. var renderPipeline = this._renderPipelines[renderPipelineName];
  48547. if (!renderPipeline) {
  48548. return;
  48549. }
  48550. renderPipeline._enableEffect(renderEffectName, cameras);
  48551. };
  48552. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  48553. var renderPipeline = this._renderPipelines[renderPipelineName];
  48554. if (!renderPipeline) {
  48555. return;
  48556. }
  48557. renderPipeline._disableEffect(renderEffectName, cameras);
  48558. };
  48559. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  48560. var renderPipeline = this._renderPipelines[renderPipelineName];
  48561. if (!renderPipeline) {
  48562. return;
  48563. }
  48564. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  48565. };
  48566. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  48567. var renderPipeline = this._renderPipelines[renderPipelineName];
  48568. if (!renderPipeline) {
  48569. return;
  48570. }
  48571. renderPipeline._disableDisplayOnlyPass(cameras);
  48572. };
  48573. PostProcessRenderPipelineManager.prototype.update = function () {
  48574. for (var renderPipelineName in this._renderPipelines) {
  48575. var pipeline = this._renderPipelines[renderPipelineName];
  48576. if (!pipeline.isSupported) {
  48577. pipeline.dispose();
  48578. delete this._renderPipelines[renderPipelineName];
  48579. }
  48580. else {
  48581. pipeline._update();
  48582. }
  48583. }
  48584. };
  48585. return PostProcessRenderPipelineManager;
  48586. }());
  48587. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  48588. })(BABYLON || (BABYLON = {}));
  48589. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  48590. var BABYLON;
  48591. (function (BABYLON) {
  48592. var PostProcessRenderPass = (function () {
  48593. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  48594. this._enabled = true;
  48595. this._refCount = 0;
  48596. this._name = name;
  48597. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  48598. this.setRenderList(renderList);
  48599. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  48600. this._renderTexture.onAfterRenderObservable.add(afterRender);
  48601. this._scene = scene;
  48602. this._renderList = renderList;
  48603. }
  48604. // private
  48605. PostProcessRenderPass.prototype._incRefCount = function () {
  48606. if (this._refCount === 0) {
  48607. this._scene.customRenderTargets.push(this._renderTexture);
  48608. }
  48609. return ++this._refCount;
  48610. };
  48611. PostProcessRenderPass.prototype._decRefCount = function () {
  48612. this._refCount--;
  48613. if (this._refCount <= 0) {
  48614. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  48615. }
  48616. return this._refCount;
  48617. };
  48618. PostProcessRenderPass.prototype._update = function () {
  48619. this.setRenderList(this._renderList);
  48620. };
  48621. // public
  48622. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  48623. this._renderTexture.renderList = renderList;
  48624. };
  48625. PostProcessRenderPass.prototype.getRenderTexture = function () {
  48626. return this._renderTexture;
  48627. };
  48628. return PostProcessRenderPass;
  48629. }());
  48630. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  48631. })(BABYLON || (BABYLON = {}));
  48632. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  48633. var BABYLON;
  48634. (function (BABYLON) {
  48635. var PostProcessRenderEffect = (function () {
  48636. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  48637. this._engine = engine;
  48638. this._name = name;
  48639. this._singleInstance = singleInstance || true;
  48640. this._getPostProcess = getPostProcess;
  48641. this._cameras = [];
  48642. this._indicesForCamera = [];
  48643. this._postProcesses = {};
  48644. this._renderPasses = {};
  48645. this._renderEffectAsPasses = {};
  48646. }
  48647. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  48648. get: function () {
  48649. for (var index in this._postProcesses) {
  48650. if (!this._postProcesses[index].isSupported) {
  48651. return false;
  48652. }
  48653. }
  48654. return true;
  48655. },
  48656. enumerable: true,
  48657. configurable: true
  48658. });
  48659. PostProcessRenderEffect.prototype._update = function () {
  48660. for (var renderPassName in this._renderPasses) {
  48661. this._renderPasses[renderPassName]._update();
  48662. }
  48663. };
  48664. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  48665. this._renderPasses[renderPass._name] = renderPass;
  48666. this._linkParameters();
  48667. };
  48668. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  48669. delete this._renderPasses[renderPass._name];
  48670. this._linkParameters();
  48671. };
  48672. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  48673. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  48674. this._linkParameters();
  48675. };
  48676. PostProcessRenderEffect.prototype.getPass = function (passName) {
  48677. for (var renderPassName in this._renderPasses) {
  48678. if (renderPassName === passName) {
  48679. return this._renderPasses[passName];
  48680. }
  48681. }
  48682. };
  48683. PostProcessRenderEffect.prototype.emptyPasses = function () {
  48684. this._renderPasses = {};
  48685. this._linkParameters();
  48686. };
  48687. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  48688. var cameraKey;
  48689. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48690. for (var i = 0; i < _cam.length; i++) {
  48691. var camera = _cam[i];
  48692. var cameraName = camera.name;
  48693. if (this._singleInstance) {
  48694. cameraKey = 0;
  48695. }
  48696. else {
  48697. cameraKey = cameraName;
  48698. }
  48699. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  48700. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  48701. if (!this._indicesForCamera[cameraName]) {
  48702. this._indicesForCamera[cameraName] = [];
  48703. }
  48704. this._indicesForCamera[cameraName].push(index);
  48705. if (this._cameras.indexOf(camera) === -1) {
  48706. this._cameras[cameraName] = camera;
  48707. }
  48708. for (var passName in this._renderPasses) {
  48709. this._renderPasses[passName]._incRefCount();
  48710. }
  48711. }
  48712. this._linkParameters();
  48713. };
  48714. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  48715. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48716. for (var i = 0; i < _cam.length; i++) {
  48717. var camera = _cam[i];
  48718. var cameraName = camera.name;
  48719. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  48720. var index = this._cameras.indexOf(cameraName);
  48721. this._indicesForCamera.splice(index, 1);
  48722. this._cameras.splice(index, 1);
  48723. for (var passName in this._renderPasses) {
  48724. this._renderPasses[passName]._decRefCount();
  48725. }
  48726. }
  48727. };
  48728. PostProcessRenderEffect.prototype._enable = function (cameras) {
  48729. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48730. for (var i = 0; i < _cam.length; i++) {
  48731. var camera = _cam[i];
  48732. var cameraName = camera.name;
  48733. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  48734. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  48735. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  48736. }
  48737. }
  48738. for (var passName in this._renderPasses) {
  48739. this._renderPasses[passName]._incRefCount();
  48740. }
  48741. }
  48742. };
  48743. PostProcessRenderEffect.prototype._disable = function (cameras) {
  48744. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48745. for (var i = 0; i < _cam.length; i++) {
  48746. var camera = _cam[i];
  48747. var cameraName = camera.Name;
  48748. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  48749. for (var passName in this._renderPasses) {
  48750. this._renderPasses[passName]._decRefCount();
  48751. }
  48752. }
  48753. };
  48754. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  48755. if (this._singleInstance) {
  48756. return this._postProcesses[0];
  48757. }
  48758. else {
  48759. return this._postProcesses[camera.name];
  48760. }
  48761. };
  48762. PostProcessRenderEffect.prototype._linkParameters = function () {
  48763. var _this = this;
  48764. for (var index in this._postProcesses) {
  48765. if (this.applyParameters) {
  48766. this.applyParameters(this._postProcesses[index]);
  48767. }
  48768. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  48769. _this._linkTextures(effect);
  48770. });
  48771. }
  48772. };
  48773. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  48774. for (var renderPassName in this._renderPasses) {
  48775. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  48776. }
  48777. for (var renderEffectName in this._renderEffectAsPasses) {
  48778. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  48779. }
  48780. };
  48781. return PostProcessRenderEffect;
  48782. }());
  48783. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  48784. })(BABYLON || (BABYLON = {}));
  48785. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  48786. var BABYLON;
  48787. (function (BABYLON) {
  48788. var PostProcessRenderPipeline = (function () {
  48789. function PostProcessRenderPipeline(engine, name) {
  48790. this._engine = engine;
  48791. this._name = name;
  48792. this._renderEffects = new Array();
  48793. this._renderEffectsForIsolatedPass = new Array();
  48794. this._cameras = [];
  48795. }
  48796. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  48797. get: function () {
  48798. for (var renderEffectName in this._renderEffects) {
  48799. if (!this._renderEffects[renderEffectName].isSupported) {
  48800. return false;
  48801. }
  48802. }
  48803. return true;
  48804. },
  48805. enumerable: true,
  48806. configurable: true
  48807. });
  48808. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  48809. this._renderEffects[renderEffect._name] = renderEffect;
  48810. };
  48811. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  48812. var renderEffects = this._renderEffects[renderEffectName];
  48813. if (!renderEffects) {
  48814. return;
  48815. }
  48816. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  48817. };
  48818. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  48819. var renderEffects = this._renderEffects[renderEffectName];
  48820. if (!renderEffects) {
  48821. return;
  48822. }
  48823. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  48824. };
  48825. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  48826. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48827. var indicesToDelete = [];
  48828. var i;
  48829. for (i = 0; i < _cam.length; i++) {
  48830. var camera = _cam[i];
  48831. var cameraName = camera.name;
  48832. if (this._cameras.indexOf(camera) === -1) {
  48833. this._cameras[cameraName] = camera;
  48834. }
  48835. else if (unique) {
  48836. indicesToDelete.push(i);
  48837. }
  48838. }
  48839. for (i = 0; i < indicesToDelete.length; i++) {
  48840. cameras.splice(indicesToDelete[i], 1);
  48841. }
  48842. for (var renderEffectName in this._renderEffects) {
  48843. this._renderEffects[renderEffectName]._attachCameras(_cam);
  48844. }
  48845. };
  48846. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  48847. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48848. for (var renderEffectName in this._renderEffects) {
  48849. this._renderEffects[renderEffectName]._detachCameras(_cam);
  48850. }
  48851. for (var i = 0; i < _cam.length; i++) {
  48852. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  48853. }
  48854. };
  48855. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  48856. var _this = this;
  48857. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48858. var pass = null;
  48859. var renderEffectName;
  48860. for (renderEffectName in this._renderEffects) {
  48861. pass = this._renderEffects[renderEffectName].getPass(passName);
  48862. if (pass != null) {
  48863. break;
  48864. }
  48865. }
  48866. if (pass === null) {
  48867. return;
  48868. }
  48869. for (renderEffectName in this._renderEffects) {
  48870. this._renderEffects[renderEffectName]._disable(_cam);
  48871. }
  48872. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  48873. for (var i = 0; i < _cam.length; i++) {
  48874. var camera = _cam[i];
  48875. var cameraName = camera.name;
  48876. 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); });
  48877. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  48878. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  48879. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  48880. }
  48881. };
  48882. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  48883. var _this = this;
  48884. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48885. for (var i = 0; i < _cam.length; i++) {
  48886. var camera = _cam[i];
  48887. var cameraName = camera.name;
  48888. 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); });
  48889. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  48890. }
  48891. for (var renderEffectName in this._renderEffects) {
  48892. this._renderEffects[renderEffectName]._enable(_cam);
  48893. }
  48894. };
  48895. PostProcessRenderPipeline.prototype._update = function () {
  48896. for (var renderEffectName in this._renderEffects) {
  48897. this._renderEffects[renderEffectName]._update();
  48898. }
  48899. for (var i = 0; i < this._cameras.length; i++) {
  48900. var cameraName = this._cameras[i].name;
  48901. if (this._renderEffectsForIsolatedPass[cameraName]) {
  48902. this._renderEffectsForIsolatedPass[cameraName]._update();
  48903. }
  48904. }
  48905. };
  48906. PostProcessRenderPipeline.prototype._reset = function () {
  48907. this._renderEffects = new Array();
  48908. this._renderEffectsForIsolatedPass = new Array();
  48909. };
  48910. PostProcessRenderPipeline.prototype.dispose = function () {
  48911. // Must be implemented by children
  48912. };
  48913. return PostProcessRenderPipeline;
  48914. }());
  48915. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  48916. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  48917. __decorate([
  48918. BABYLON.serialize()
  48919. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  48920. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  48921. })(BABYLON || (BABYLON = {}));
  48922. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  48923. var BABYLON;
  48924. (function (BABYLON) {
  48925. var DepthRenderer = (function () {
  48926. function DepthRenderer(scene, type) {
  48927. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  48928. var _this = this;
  48929. this._viewMatrix = BABYLON.Matrix.Zero();
  48930. this._projectionMatrix = BABYLON.Matrix.Zero();
  48931. this._transformMatrix = BABYLON.Matrix.Zero();
  48932. this._worldViewProjection = BABYLON.Matrix.Zero();
  48933. this._scene = scene;
  48934. var engine = scene.getEngine();
  48935. // Render target
  48936. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  48937. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48938. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48939. this._depthMap.refreshRate = 1;
  48940. this._depthMap.renderParticles = false;
  48941. this._depthMap.renderList = null;
  48942. // set default depth value to 1.0 (far away)
  48943. this._depthMap.onClearObservable.add(function (engine) {
  48944. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  48945. });
  48946. // Custom render function
  48947. var renderSubMesh = function (subMesh) {
  48948. var mesh = subMesh.getRenderingMesh();
  48949. var scene = _this._scene;
  48950. var engine = scene.getEngine();
  48951. // Culling
  48952. engine.setState(subMesh.getMaterial().backFaceCulling);
  48953. // Managing instances
  48954. var batch = mesh._getInstancesRenderList(subMesh._id);
  48955. if (batch.mustReturn) {
  48956. return;
  48957. }
  48958. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  48959. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  48960. engine.enableEffect(_this._effect);
  48961. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  48962. var material = subMesh.getMaterial();
  48963. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  48964. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  48965. // Alpha test
  48966. if (material && material.needAlphaTesting()) {
  48967. var alphaTexture = material.getAlphaTestTexture();
  48968. _this._effect.setTexture("diffuseSampler", alphaTexture);
  48969. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48970. }
  48971. // Bones
  48972. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48973. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48974. }
  48975. // Draw
  48976. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  48977. }
  48978. };
  48979. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  48980. var index;
  48981. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48982. renderSubMesh(opaqueSubMeshes.data[index]);
  48983. }
  48984. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48985. renderSubMesh(alphaTestSubMeshes.data[index]);
  48986. }
  48987. };
  48988. }
  48989. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  48990. var material = subMesh.getMaterial();
  48991. if (material.disableDepthWrite) {
  48992. return false;
  48993. }
  48994. var defines = [];
  48995. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48996. var mesh = subMesh.getMesh();
  48997. var scene = mesh.getScene();
  48998. // Alpha test
  48999. if (material && material.needAlphaTesting()) {
  49000. defines.push("#define ALPHATEST");
  49001. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49002. attribs.push(BABYLON.VertexBuffer.UVKind);
  49003. defines.push("#define UV1");
  49004. }
  49005. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  49006. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  49007. defines.push("#define UV2");
  49008. }
  49009. }
  49010. // Bones
  49011. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49012. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49013. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49014. if (mesh.numBoneInfluencers > 4) {
  49015. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49016. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49017. }
  49018. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49019. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49020. }
  49021. else {
  49022. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49023. }
  49024. // Instances
  49025. if (useInstances) {
  49026. defines.push("#define INSTANCES");
  49027. attribs.push("world0");
  49028. attribs.push("world1");
  49029. attribs.push("world2");
  49030. attribs.push("world3");
  49031. }
  49032. // Get correct effect
  49033. var join = defines.join("\n");
  49034. if (this._cachedDefines !== join) {
  49035. this._cachedDefines = join;
  49036. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  49037. }
  49038. return this._effect.isReady();
  49039. };
  49040. DepthRenderer.prototype.getDepthMap = function () {
  49041. return this._depthMap;
  49042. };
  49043. // Methods
  49044. DepthRenderer.prototype.dispose = function () {
  49045. this._depthMap.dispose();
  49046. };
  49047. return DepthRenderer;
  49048. }());
  49049. BABYLON.DepthRenderer = DepthRenderer;
  49050. })(BABYLON || (BABYLON = {}));
  49051. //# sourceMappingURL=babylon.depthRenderer.js.map
  49052. var BABYLON;
  49053. (function (BABYLON) {
  49054. var SSAORenderingPipeline = (function (_super) {
  49055. __extends(SSAORenderingPipeline, _super);
  49056. /**
  49057. * @constructor
  49058. * @param {string} name - The rendering pipeline name
  49059. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49060. * @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 }
  49061. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49062. */
  49063. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  49064. var _this = _super.call(this, scene.getEngine(), name) || this;
  49065. // Members
  49066. /**
  49067. * The PassPostProcess id in the pipeline that contains the original scene color
  49068. * @type {string}
  49069. */
  49070. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  49071. /**
  49072. * The SSAO PostProcess id in the pipeline
  49073. * @type {string}
  49074. */
  49075. _this.SSAORenderEffect = "SSAORenderEffect";
  49076. /**
  49077. * The horizontal blur PostProcess id in the pipeline
  49078. * @type {string}
  49079. */
  49080. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  49081. /**
  49082. * The vertical blur PostProcess id in the pipeline
  49083. * @type {string}
  49084. */
  49085. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  49086. /**
  49087. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  49088. * @type {string}
  49089. */
  49090. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  49091. /**
  49092. * The output strength of the SSAO post-process. Default value is 1.0.
  49093. * @type {number}
  49094. */
  49095. _this.totalStrength = 1.0;
  49096. /**
  49097. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  49098. * @type {number}
  49099. */
  49100. _this.radius = 0.0001;
  49101. /**
  49102. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  49103. * Must not be equal to fallOff and superior to fallOff.
  49104. * Default value is 0.975
  49105. * @type {number}
  49106. */
  49107. _this.area = 0.0075;
  49108. /**
  49109. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  49110. * Must not be equal to area and inferior to area.
  49111. * Default value is 0.0
  49112. * @type {number}
  49113. */
  49114. _this.fallOff = 0.000001;
  49115. /**
  49116. * The base color of the SSAO post-process
  49117. * The final result is "base + ssao" between [0, 1]
  49118. * @type {number}
  49119. */
  49120. _this.base = 0.5;
  49121. _this._firstUpdate = true;
  49122. _this._scene = scene;
  49123. // Set up assets
  49124. _this._createRandomTexture();
  49125. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  49126. var ssaoRatio = ratio.ssaoRatio || ratio;
  49127. var combineRatio = ratio.combineRatio || ratio;
  49128. _this._ratio = {
  49129. ssaoRatio: ssaoRatio,
  49130. combineRatio: combineRatio
  49131. };
  49132. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  49133. _this._createSSAOPostProcess(ssaoRatio);
  49134. _this._createBlurPostProcess(ssaoRatio);
  49135. _this._createSSAOCombinePostProcess(combineRatio);
  49136. // Set up pipeline
  49137. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  49138. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  49139. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  49140. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  49141. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  49142. // Finish
  49143. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49144. if (cameras)
  49145. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49146. return _this;
  49147. }
  49148. // Public Methods
  49149. /**
  49150. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  49151. */
  49152. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  49153. if (disableDepthRender === void 0) { disableDepthRender = false; }
  49154. for (var i = 0; i < this._scene.cameras.length; i++) {
  49155. var camera = this._scene.cameras[i];
  49156. this._originalColorPostProcess.dispose(camera);
  49157. this._ssaoPostProcess.dispose(camera);
  49158. this._blurHPostProcess.dispose(camera);
  49159. this._blurVPostProcess.dispose(camera);
  49160. this._ssaoCombinePostProcess.dispose(camera);
  49161. }
  49162. this._randomTexture.dispose();
  49163. if (disableDepthRender)
  49164. this._scene.disableDepthRenderer();
  49165. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49166. _super.prototype.dispose.call(this);
  49167. };
  49168. // Private Methods
  49169. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  49170. var _this = this;
  49171. /*
  49172. var samplerOffsets = [
  49173. -8.0, -6.0, -4.0, -2.0,
  49174. 0.0,
  49175. 2.0, 4.0, 6.0, 8.0
  49176. ];
  49177. */
  49178. var samples = 16;
  49179. var samplerOffsets = [];
  49180. for (var i = -8; i < 8; i++) {
  49181. samplerOffsets.push(i * 2);
  49182. }
  49183. 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");
  49184. this._blurHPostProcess.onApply = function (effect) {
  49185. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  49186. effect.setTexture("depthSampler", _this._depthTexture);
  49187. if (_this._firstUpdate) {
  49188. effect.setArray("samplerOffsets", samplerOffsets);
  49189. }
  49190. };
  49191. 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");
  49192. this._blurVPostProcess.onApply = function (effect) {
  49193. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  49194. effect.setTexture("depthSampler", _this._depthTexture);
  49195. if (_this._firstUpdate) {
  49196. effect.setArray("samplerOffsets", samplerOffsets);
  49197. _this._firstUpdate = false;
  49198. }
  49199. };
  49200. };
  49201. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  49202. var _this = this;
  49203. var numSamples = 16;
  49204. var sampleSphere = [
  49205. 0.5381, 0.1856, -0.4319,
  49206. 0.1379, 0.2486, 0.4430,
  49207. 0.3371, 0.5679, -0.0057,
  49208. -0.6999, -0.0451, -0.0019,
  49209. 0.0689, -0.1598, -0.8547,
  49210. 0.0560, 0.0069, -0.1843,
  49211. -0.0146, 0.1402, 0.0762,
  49212. 0.0100, -0.1924, -0.0344,
  49213. -0.3577, -0.5301, -0.4358,
  49214. -0.3169, 0.1063, 0.0158,
  49215. 0.0103, -0.5869, 0.0046,
  49216. -0.0897, -0.4940, 0.3287,
  49217. 0.7119, -0.0154, -0.0918,
  49218. -0.0533, 0.0596, -0.5411,
  49219. 0.0352, -0.0631, 0.5460,
  49220. -0.4776, 0.2847, -0.0271
  49221. ];
  49222. var samplesFactor = 1.0 / numSamples;
  49223. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  49224. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  49225. "area", "fallOff", "base", "range", "viewport"
  49226. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  49227. var viewport = new BABYLON.Vector2(0, 0);
  49228. this._ssaoPostProcess.onApply = function (effect) {
  49229. if (_this._firstUpdate) {
  49230. effect.setArray3("sampleSphere", sampleSphere);
  49231. effect.setFloat("samplesFactor", samplesFactor);
  49232. effect.setFloat("randTextureTiles", 4.0);
  49233. }
  49234. effect.setFloat("totalStrength", _this.totalStrength);
  49235. effect.setFloat("radius", _this.radius);
  49236. effect.setFloat("area", _this.area);
  49237. effect.setFloat("fallOff", _this.fallOff);
  49238. effect.setFloat("base", _this.base);
  49239. effect.setTexture("textureSampler", _this._depthTexture);
  49240. effect.setTexture("randomSampler", _this._randomTexture);
  49241. };
  49242. };
  49243. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  49244. var _this = this;
  49245. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49246. this._ssaoCombinePostProcess.onApply = function (effect) {
  49247. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  49248. };
  49249. };
  49250. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  49251. var size = 512;
  49252. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  49253. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49254. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49255. var context = this._randomTexture.getContext();
  49256. var rand = function (min, max) {
  49257. return Math.random() * (max - min) + min;
  49258. };
  49259. var randVector = BABYLON.Vector3.Zero();
  49260. for (var x = 0; x < size; x++) {
  49261. for (var y = 0; y < size; y++) {
  49262. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  49263. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  49264. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  49265. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  49266. context.fillRect(x, y, 1, 1);
  49267. }
  49268. }
  49269. this._randomTexture.update(false);
  49270. };
  49271. return SSAORenderingPipeline;
  49272. }(BABYLON.PostProcessRenderPipeline));
  49273. __decorate([
  49274. BABYLON.serialize()
  49275. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  49276. __decorate([
  49277. BABYLON.serialize()
  49278. ], SSAORenderingPipeline.prototype, "radius", void 0);
  49279. __decorate([
  49280. BABYLON.serialize()
  49281. ], SSAORenderingPipeline.prototype, "area", void 0);
  49282. __decorate([
  49283. BABYLON.serialize()
  49284. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  49285. __decorate([
  49286. BABYLON.serialize()
  49287. ], SSAORenderingPipeline.prototype, "base", void 0);
  49288. __decorate([
  49289. BABYLON.serialize()
  49290. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  49291. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  49292. })(BABYLON || (BABYLON = {}));
  49293. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  49294. var BABYLON;
  49295. (function (BABYLON) {
  49296. var SSAO2RenderingPipeline = (function (_super) {
  49297. __extends(SSAO2RenderingPipeline, _super);
  49298. /**
  49299. * @constructor
  49300. * @param {string} name - The rendering pipeline name
  49301. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49302. * @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 }
  49303. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49304. */
  49305. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  49306. var _this = _super.call(this, scene.getEngine(), name) || this;
  49307. // Members
  49308. /**
  49309. * The PassPostProcess id in the pipeline that contains the original scene color
  49310. * @type {string}
  49311. */
  49312. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  49313. /**
  49314. * The SSAO PostProcess id in the pipeline
  49315. * @type {string}
  49316. */
  49317. _this.SSAORenderEffect = "SSAORenderEffect";
  49318. /**
  49319. * The horizontal blur PostProcess id in the pipeline
  49320. * @type {string}
  49321. */
  49322. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  49323. /**
  49324. * The vertical blur PostProcess id in the pipeline
  49325. * @type {string}
  49326. */
  49327. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  49328. /**
  49329. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  49330. * @type {string}
  49331. */
  49332. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  49333. /**
  49334. * The output strength of the SSAO post-process. Default value is 1.0.
  49335. * @type {number}
  49336. */
  49337. _this.totalStrength = 1.0;
  49338. /**
  49339. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  49340. * @type {number}
  49341. */
  49342. _this.maxZ = 100.0;
  49343. /**
  49344. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  49345. * @type {number}
  49346. */
  49347. _this.minZAspect = 0.2;
  49348. /**
  49349. * Number of samples used for the SSAO calculations. Default value is 8
  49350. * @type {number}
  49351. */
  49352. _this._samples = 8;
  49353. /**
  49354. * Are we using bilateral blur ?
  49355. * @type {boolean}
  49356. */
  49357. _this._expensiveBlur = true;
  49358. /**
  49359. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  49360. * @type {number}
  49361. */
  49362. _this.radius = 2.0;
  49363. /**
  49364. * The base color of the SSAO post-process
  49365. * The final result is "base + ssao" between [0, 1]
  49366. * @type {number}
  49367. */
  49368. _this.base = 0.1;
  49369. _this._firstUpdate = true;
  49370. _this._scene = scene;
  49371. if (!_this.isSupported) {
  49372. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  49373. return _this;
  49374. }
  49375. var ssaoRatio = ratio.ssaoRatio || ratio;
  49376. var blurRatio = ratio.blurRatio || ratio;
  49377. _this._ratio = {
  49378. ssaoRatio: ssaoRatio,
  49379. blurRatio: blurRatio
  49380. };
  49381. // Set up assets
  49382. _this._createRandomTexture();
  49383. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  49384. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  49385. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  49386. _this._createSSAOPostProcess(1.0);
  49387. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  49388. _this._createSSAOCombinePostProcess(blurRatio);
  49389. // Set up pipeline
  49390. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  49391. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  49392. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  49393. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  49394. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  49395. // Finish
  49396. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49397. if (cameras)
  49398. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49399. return _this;
  49400. }
  49401. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  49402. get: function () {
  49403. return this._samples;
  49404. },
  49405. set: function (n) {
  49406. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  49407. this._samples = n;
  49408. this._sampleSphere = this._generateHemisphere();
  49409. this._firstUpdate = true;
  49410. },
  49411. enumerable: true,
  49412. configurable: true
  49413. });
  49414. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  49415. get: function () {
  49416. return this._expensiveBlur;
  49417. },
  49418. set: function (b) {
  49419. 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"]);
  49420. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  49421. this._expensiveBlur = b;
  49422. this._firstUpdate = true;
  49423. },
  49424. enumerable: true,
  49425. configurable: true
  49426. });
  49427. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  49428. /**
  49429. * Support test.
  49430. * @type {boolean}
  49431. */
  49432. get: function () {
  49433. var engine = BABYLON.Engine.LastCreatedEngine;
  49434. return engine.webGLVersion > 1;
  49435. },
  49436. enumerable: true,
  49437. configurable: true
  49438. });
  49439. // Public Methods
  49440. /**
  49441. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  49442. */
  49443. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  49444. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  49445. for (var i = 0; i < this._scene.cameras.length; i++) {
  49446. var camera = this._scene.cameras[i];
  49447. this._originalColorPostProcess.dispose(camera);
  49448. this._ssaoPostProcess.dispose(camera);
  49449. this._blurHPostProcess.dispose(camera);
  49450. this._blurVPostProcess.dispose(camera);
  49451. this._ssaoCombinePostProcess.dispose(camera);
  49452. }
  49453. this._randomTexture.dispose();
  49454. if (disableGeometryBufferRenderer)
  49455. this._scene.disableGeometryBufferRenderer();
  49456. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49457. _super.prototype.dispose.call(this);
  49458. };
  49459. // Private Methods
  49460. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  49461. var _this = this;
  49462. var samples = 16;
  49463. this._samplerOffsets = [];
  49464. var expensive = this.expensiveBlur;
  49465. for (var i = -8; i < 8; i++) {
  49466. this._samplerOffsets.push(i * 2 + 0.5);
  49467. }
  49468. 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");
  49469. this._blurHPostProcess.onApply = function (effect) {
  49470. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  49471. effect.setFloat("near", _this._scene.activeCamera.minZ);
  49472. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  49473. effect.setFloat("radius", _this.radius);
  49474. effect.setTexture("depthSampler", _this._depthTexture);
  49475. if (_this._firstUpdate) {
  49476. effect.setArray("samplerOffsets", _this._samplerOffsets);
  49477. }
  49478. };
  49479. 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");
  49480. this._blurVPostProcess.onApply = function (effect) {
  49481. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  49482. effect.setFloat("near", _this._scene.activeCamera.minZ);
  49483. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  49484. effect.setFloat("radius", _this.radius);
  49485. effect.setTexture("depthSampler", _this._depthTexture);
  49486. if (_this._firstUpdate) {
  49487. effect.setArray("samplerOffsets", _this._samplerOffsets);
  49488. _this._firstUpdate = false;
  49489. }
  49490. };
  49491. };
  49492. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  49493. var numSamples = this.samples;
  49494. var result = [];
  49495. var vector, scale;
  49496. var rand = function (min, max) {
  49497. return Math.random() * (max - min) + min;
  49498. };
  49499. var lerp = function (start, end, percent) {
  49500. return (start + percent * (end - start));
  49501. };
  49502. var i = 0;
  49503. var normal = new BABYLON.Vector3(0, 0, 1);
  49504. while (i < numSamples) {
  49505. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  49506. vector.normalize();
  49507. scale = i / numSamples;
  49508. scale = lerp(0.1, 1.0, scale * scale);
  49509. vector.scaleInPlace(scale);
  49510. result.push(vector.x, vector.y, vector.z);
  49511. i++;
  49512. }
  49513. return result;
  49514. };
  49515. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  49516. var _this = this;
  49517. var numSamples = this.samples;
  49518. this._sampleSphere = this._generateHemisphere();
  49519. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  49520. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  49521. "base", "range", "projection", "near", "far", "texelSize",
  49522. "xViewport", "yViewport", "maxZ", "minZAspect"
  49523. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  49524. this._ssaoPostProcess.onApply = function (effect) {
  49525. if (_this._firstUpdate) {
  49526. effect.setArray3("sampleSphere", _this._sampleSphere);
  49527. effect.setFloat("randTextureTiles", 4.0);
  49528. }
  49529. effect.setFloat("samplesFactor", 1 / _this.samples);
  49530. effect.setFloat("totalStrength", _this.totalStrength);
  49531. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  49532. effect.setFloat("radius", _this.radius);
  49533. effect.setFloat("maxZ", _this.maxZ);
  49534. effect.setFloat("minZAspect", _this.minZAspect);
  49535. effect.setFloat("base", _this.base);
  49536. effect.setFloat("near", _this._scene.activeCamera.minZ);
  49537. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  49538. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.activeCamera.minZ * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  49539. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.activeCamera.minZ);
  49540. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  49541. effect.setTexture("textureSampler", _this._depthTexture);
  49542. effect.setTexture("normalSampler", _this._normalTexture);
  49543. effect.setTexture("randomSampler", _this._randomTexture);
  49544. };
  49545. };
  49546. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  49547. var _this = this;
  49548. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49549. this._ssaoCombinePostProcess.onApply = function (effect) {
  49550. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  49551. };
  49552. };
  49553. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  49554. var size = 512;
  49555. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  49556. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49557. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49558. var context = this._randomTexture.getContext();
  49559. var rand = function (min, max) {
  49560. return Math.random() * (max - min) + min;
  49561. };
  49562. var randVector = BABYLON.Vector3.Zero();
  49563. for (var x = 0; x < size; x++) {
  49564. for (var y = 0; y < size; y++) {
  49565. randVector.x = rand(0.0, 1.0);
  49566. randVector.y = rand(0.0, 1.0);
  49567. randVector.z = 0.0;
  49568. randVector.normalize();
  49569. randVector.scaleInPlace(255);
  49570. randVector.x = Math.floor(randVector.x);
  49571. randVector.y = Math.floor(randVector.y);
  49572. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  49573. context.fillRect(x, y, 1, 1);
  49574. }
  49575. }
  49576. this._randomTexture.update(false);
  49577. };
  49578. return SSAO2RenderingPipeline;
  49579. }(BABYLON.PostProcessRenderPipeline));
  49580. __decorate([
  49581. BABYLON.serialize()
  49582. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  49583. __decorate([
  49584. BABYLON.serialize()
  49585. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  49586. __decorate([
  49587. BABYLON.serialize()
  49588. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  49589. __decorate([
  49590. BABYLON.serialize("samples")
  49591. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  49592. __decorate([
  49593. BABYLON.serialize("expensiveBlur")
  49594. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  49595. __decorate([
  49596. BABYLON.serialize()
  49597. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  49598. __decorate([
  49599. BABYLON.serialize()
  49600. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  49601. __decorate([
  49602. BABYLON.serialize()
  49603. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  49604. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  49605. })(BABYLON || (BABYLON = {}));
  49606. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  49607. // BABYLON.JS Chromatic Aberration GLSL Shader
  49608. // Author: Olivier Guyot
  49609. // Separates very slightly R, G and B colors on the edges of the screen
  49610. // Inspired by Francois Tarlier & Martins Upitis
  49611. var BABYLON;
  49612. (function (BABYLON) {
  49613. var LensRenderingPipeline = (function (_super) {
  49614. __extends(LensRenderingPipeline, _super);
  49615. /**
  49616. * @constructor
  49617. *
  49618. * Effect parameters are as follow:
  49619. * {
  49620. * chromatic_aberration: number; // from 0 to x (1 for realism)
  49621. * edge_blur: number; // from 0 to x (1 for realism)
  49622. * distortion: number; // from 0 to x (1 for realism)
  49623. * grain_amount: number; // from 0 to 1
  49624. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  49625. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  49626. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  49627. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  49628. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  49629. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  49630. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  49631. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  49632. * }
  49633. * Note: if an effect parameter is unset, effect is disabled
  49634. *
  49635. * @param {string} name - The rendering pipeline name
  49636. * @param {object} parameters - An object containing all parameters (see above)
  49637. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49638. * @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)
  49639. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49640. */
  49641. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  49642. if (ratio === void 0) { ratio = 1.0; }
  49643. var _this = _super.call(this, scene.getEngine(), name) || this;
  49644. // Lens effects can be of the following:
  49645. // - chromatic aberration (slight shift of RGB colors)
  49646. // - blur on the edge of the lens
  49647. // - lens distortion
  49648. // - depth-of-field blur & highlights enhancing
  49649. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  49650. // - grain effect (noise or custom texture)
  49651. // Two additional texture samplers are needed:
  49652. // - depth map (for depth-of-field)
  49653. // - grain texture
  49654. /**
  49655. * The chromatic aberration PostProcess id in the pipeline
  49656. * @type {string}
  49657. */
  49658. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  49659. /**
  49660. * The highlights enhancing PostProcess id in the pipeline
  49661. * @type {string}
  49662. */
  49663. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  49664. /**
  49665. * The depth-of-field PostProcess id in the pipeline
  49666. * @type {string}
  49667. */
  49668. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  49669. _this._scene = scene;
  49670. // Fetch texture samplers
  49671. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  49672. if (parameters.grain_texture) {
  49673. _this._grainTexture = parameters.grain_texture;
  49674. }
  49675. else {
  49676. _this._createGrainTexture();
  49677. }
  49678. // save parameters
  49679. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  49680. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  49681. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  49682. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  49683. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  49684. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  49685. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  49686. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  49687. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  49688. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  49689. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  49690. // Create effects
  49691. _this._createChromaticAberrationPostProcess(ratio);
  49692. _this._createHighlightsPostProcess(ratio);
  49693. _this._createDepthOfFieldPostProcess(ratio / 4);
  49694. // Set up pipeline
  49695. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  49696. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  49697. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  49698. if (_this._highlightsGain === -1) {
  49699. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  49700. }
  49701. // Finish
  49702. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49703. if (cameras) {
  49704. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49705. }
  49706. return _this;
  49707. }
  49708. // public methods (self explanatory)
  49709. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  49710. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  49711. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  49712. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  49713. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  49714. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  49715. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  49716. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  49717. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  49718. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  49719. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  49720. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  49721. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  49722. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  49723. };
  49724. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  49725. this._highlightsPostProcess.updateEffect();
  49726. };
  49727. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  49728. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  49729. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  49730. this._highlightsGain = amount;
  49731. };
  49732. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  49733. if (this._highlightsGain === -1) {
  49734. this._highlightsGain = 1.0;
  49735. }
  49736. this._highlightsThreshold = amount;
  49737. };
  49738. LensRenderingPipeline.prototype.disableHighlights = function () {
  49739. this._highlightsGain = -1;
  49740. };
  49741. /**
  49742. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  49743. */
  49744. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  49745. if (disableDepthRender === void 0) { disableDepthRender = false; }
  49746. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49747. this._chromaticAberrationPostProcess = undefined;
  49748. this._highlightsPostProcess = undefined;
  49749. this._depthOfFieldPostProcess = undefined;
  49750. this._grainTexture.dispose();
  49751. if (disableDepthRender)
  49752. this._scene.disableDepthRenderer();
  49753. };
  49754. // colors shifting and distortion
  49755. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  49756. var _this = this;
  49757. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  49758. [], // samplers
  49759. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49760. this._chromaticAberrationPostProcess.onApply = function (effect) {
  49761. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  49762. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  49763. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  49764. };
  49765. };
  49766. // highlights enhancing
  49767. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  49768. var _this = this;
  49769. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  49770. [], // samplers
  49771. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  49772. this._highlightsPostProcess.onApply = function (effect) {
  49773. effect.setFloat('gain', _this._highlightsGain);
  49774. effect.setFloat('threshold', _this._highlightsThreshold);
  49775. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  49776. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  49777. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  49778. };
  49779. };
  49780. // colors shifting and distortion
  49781. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  49782. var _this = this;
  49783. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  49784. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  49785. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  49786. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49787. this._depthOfFieldPostProcess.onApply = function (effect) {
  49788. effect.setTexture("depthSampler", _this._depthTexture);
  49789. effect.setTexture("grainSampler", _this._grainTexture);
  49790. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  49791. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  49792. effect.setFloat('grain_amount', _this._grainAmount);
  49793. effect.setBool('blur_noise', _this._blurNoise);
  49794. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  49795. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  49796. effect.setFloat('distortion', _this._distortion);
  49797. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  49798. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  49799. effect.setFloat('aperture', _this._dofAperture);
  49800. effect.setFloat('darken', _this._dofDarken);
  49801. effect.setFloat('edge_blur', _this._edgeBlur);
  49802. effect.setBool('highlights', (_this._highlightsGain !== -1));
  49803. effect.setFloat('near', _this._scene.activeCamera.minZ);
  49804. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  49805. };
  49806. };
  49807. // creates a black and white random noise texture, 512x512
  49808. LensRenderingPipeline.prototype._createGrainTexture = function () {
  49809. var size = 512;
  49810. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49811. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49812. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49813. var context = this._grainTexture.getContext();
  49814. var rand = function (min, max) {
  49815. return Math.random() * (max - min) + min;
  49816. };
  49817. var value;
  49818. for (var x = 0; x < size; x++) {
  49819. for (var y = 0; y < size; y++) {
  49820. value = Math.floor(rand(0.42, 0.58) * 255);
  49821. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  49822. context.fillRect(x, y, 1, 1);
  49823. }
  49824. }
  49825. this._grainTexture.update(false);
  49826. };
  49827. return LensRenderingPipeline;
  49828. }(BABYLON.PostProcessRenderPipeline));
  49829. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  49830. })(BABYLON || (BABYLON = {}));
  49831. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  49832. var BABYLON;
  49833. (function (BABYLON) {
  49834. var StandardRenderingPipeline = (function (_super) {
  49835. __extends(StandardRenderingPipeline, _super);
  49836. /**
  49837. * @constructor
  49838. * @param {string} name - The rendering pipeline name
  49839. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49840. * @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)
  49841. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  49842. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49843. */
  49844. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  49845. if (originalPostProcess === void 0) { originalPostProcess = null; }
  49846. var _this = _super.call(this, scene.getEngine(), name) || this;
  49847. _this.downSampleX4PostProcess = null;
  49848. _this.brightPassPostProcess = null;
  49849. _this.gaussianBlurHPostProcesses = [];
  49850. _this.gaussianBlurVPostProcesses = [];
  49851. _this.textureAdderPostProcess = null;
  49852. _this.luminancePostProcess = null;
  49853. _this.luminanceDownSamplePostProcesses = [];
  49854. _this.hdrPostProcess = null;
  49855. _this.textureAdderFinalPostProcess = null;
  49856. _this.lensFlareFinalPostProcess = null;
  49857. _this.hdrFinalPostProcess = null;
  49858. _this.lensFlarePostProcess = null;
  49859. _this.lensFlareComposePostProcess = null;
  49860. _this.motionBlurPostProcess = null;
  49861. _this.depthOfFieldPostProcess = null;
  49862. // Values
  49863. _this.brightThreshold = 1.0;
  49864. _this.blurWidth = 2.0;
  49865. _this.horizontalBlur = false;
  49866. _this.gaussianCoefficient = 0.25;
  49867. _this.gaussianMean = 1.0;
  49868. _this.gaussianStandardDeviation = 1.0;
  49869. _this.exposure = 1.0;
  49870. _this.lensTexture = null;
  49871. _this.hdrMinimumLuminance = 1.0;
  49872. _this.hdrDecreaseRate = 0.5;
  49873. _this.hdrIncreaseRate = 0.5;
  49874. _this.lensColorTexture = null;
  49875. _this.lensFlareStrength = 20.0;
  49876. _this.lensFlareGhostDispersal = 1.4;
  49877. _this.lensFlareHaloWidth = 0.7;
  49878. _this.lensFlareDistortionStrength = 16.0;
  49879. _this.lensStarTexture = null;
  49880. _this.lensFlareDirtTexture = null;
  49881. _this.depthOfFieldDistance = 10.0;
  49882. _this.depthOfFieldBlurWidth = 2.0;
  49883. _this.motionStrength = 1.0;
  49884. // IAnimatable
  49885. _this.animations = [];
  49886. _this._depthRenderer = null;
  49887. _this._currentDepthOfFieldSource = null;
  49888. _this._currentHDRSource = null;
  49889. _this._hdrCurrentLuminance = 1.0;
  49890. _this._motionBlurSamples = 64;
  49891. // Getters and setters
  49892. _this._bloomEnabled = true;
  49893. _this._depthOfFieldEnabled = true;
  49894. _this._lensFlareEnabled = true;
  49895. _this._hdrEnabled = true;
  49896. _this._motionBlurEnabled = true;
  49897. _this._cameras = cameras || [];
  49898. // Initialize
  49899. _this._scene = scene;
  49900. // Misc
  49901. var floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49902. // Create pass post-process
  49903. if (!originalPostProcess) {
  49904. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", floatTextureType);
  49905. }
  49906. else {
  49907. _this.originalPostProcess = originalPostProcess;
  49908. }
  49909. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  49910. // Create down sample X4 post-process
  49911. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  49912. // Create bright pass post-process
  49913. _this._createBrightPassPostProcess(scene, ratio / 2);
  49914. // Create gaussian blur post-processes (down sampling blurs)
  49915. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  49916. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  49917. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  49918. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  49919. // Create texture adder post-process
  49920. _this._createTextureAdderPostProcess(scene, ratio);
  49921. // Create depth-of-field source post-process
  49922. _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);
  49923. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  49924. // Create lens flare post-process
  49925. _this._createLensFlarePostProcess(scene, ratio);
  49926. // Create depth-of-field source post-process post lens-flare and disable it now
  49927. _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);
  49928. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  49929. // Create luminance
  49930. _this._createLuminancePostProcesses(scene, floatTextureType);
  49931. // Create HDR
  49932. _this._createHdrPostProcess(scene, ratio);
  49933. // Create depth-of-field source post-process post hdr and disable it now
  49934. _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);
  49935. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  49936. // Create gaussian blur used by depth-of-field
  49937. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  49938. // Create depth-of-field post-process
  49939. _this._createDepthOfFieldPostProcess(scene, ratio);
  49940. // Create motion blur post-process
  49941. _this._createMotionBlurPostProcess(scene, ratio);
  49942. // Finish
  49943. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49944. if (cameras !== null) {
  49945. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49946. }
  49947. // Deactivate
  49948. _this.LensFlareEnabled = false;
  49949. _this.DepthOfFieldEnabled = false;
  49950. _this.HDREnabled = false;
  49951. _this.MotionBlurEnabled = false;
  49952. return _this;
  49953. }
  49954. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  49955. get: function () {
  49956. return this._bloomEnabled;
  49957. },
  49958. set: function (enabled) {
  49959. if (enabled && !this._bloomEnabled) {
  49960. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDownSampleX4", this._cameras);
  49961. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRBrightPass", this._cameras);
  49962. for (var i = 0; i < this.gaussianBlurHPostProcesses.length - 1; i++) {
  49963. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._cameras);
  49964. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._cameras);
  49965. }
  49966. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRTextureAdder", this._cameras);
  49967. }
  49968. else if (!enabled && this._bloomEnabled) {
  49969. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDownSampleX4", this._cameras);
  49970. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRBrightPass", this._cameras);
  49971. for (var i = 0; i < this.gaussianBlurHPostProcesses.length - 1; i++) {
  49972. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._cameras);
  49973. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._cameras);
  49974. }
  49975. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRTextureAdder", this._cameras);
  49976. }
  49977. this._bloomEnabled = enabled;
  49978. },
  49979. enumerable: true,
  49980. configurable: true
  49981. });
  49982. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  49983. get: function () {
  49984. return this._depthOfFieldEnabled;
  49985. },
  49986. set: function (enabled) {
  49987. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  49988. if (enabled && !this._depthOfFieldEnabled) {
  49989. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  49990. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  49991. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  49992. this._depthRenderer = this._scene.enableDepthRenderer();
  49993. }
  49994. else if (!enabled && this._depthOfFieldEnabled) {
  49995. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  49996. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  49997. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  49998. }
  49999. this._depthOfFieldEnabled = enabled;
  50000. },
  50001. enumerable: true,
  50002. configurable: true
  50003. });
  50004. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  50005. get: function () {
  50006. return this._lensFlareEnabled;
  50007. },
  50008. set: function (enabled) {
  50009. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  50010. if (enabled && !this._lensFlareEnabled) {
  50011. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  50012. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  50013. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  50014. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  50015. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  50016. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  50017. }
  50018. else if (!enabled && this._lensFlareEnabled) {
  50019. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  50020. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  50021. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  50022. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  50023. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  50024. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  50025. }
  50026. this._lensFlareEnabled = enabled;
  50027. },
  50028. enumerable: true,
  50029. configurable: true
  50030. });
  50031. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  50032. get: function () {
  50033. return this._hdrEnabled;
  50034. },
  50035. set: function (enabled) {
  50036. if (enabled && !this._hdrEnabled) {
  50037. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  50038. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  50039. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  50040. }
  50041. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  50042. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  50043. }
  50044. else if (!enabled && this._hdrEnabled) {
  50045. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  50046. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  50047. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  50048. }
  50049. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  50050. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  50051. }
  50052. this._hdrEnabled = enabled;
  50053. },
  50054. enumerable: true,
  50055. configurable: true
  50056. });
  50057. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  50058. get: function () {
  50059. return this._motionBlurEnabled;
  50060. },
  50061. set: function (enabled) {
  50062. if (enabled && !this._motionBlurEnabled) {
  50063. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRMotionBlur", this._scene.cameras);
  50064. this._depthRenderer = this._scene.enableDepthRenderer();
  50065. }
  50066. else if (!enabled && this._motionBlurEnabled) {
  50067. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRMotionBlur", this._scene.cameras);
  50068. }
  50069. this._motionBlurEnabled = enabled;
  50070. },
  50071. enumerable: true,
  50072. configurable: true
  50073. });
  50074. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  50075. get: function () {
  50076. return this._motionBlurSamples;
  50077. },
  50078. set: function (samples) {
  50079. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  50080. this._motionBlurSamples = samples;
  50081. },
  50082. enumerable: true,
  50083. configurable: true
  50084. });
  50085. // Down Sample X4 Post-Processs
  50086. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  50087. var _this = this;
  50088. var downSampleX4Offsets = new Array(32);
  50089. 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);
  50090. this.downSampleX4PostProcess.onApply = function (effect) {
  50091. var id = 0;
  50092. for (var i = -2; i < 2; i++) {
  50093. for (var j = -2; j < 2; j++) {
  50094. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  50095. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  50096. id += 2;
  50097. }
  50098. }
  50099. effect.setArray2("dsOffsets", downSampleX4Offsets);
  50100. };
  50101. // Add to pipeline
  50102. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  50103. };
  50104. // Brightpass Post-Process
  50105. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  50106. var _this = this;
  50107. var brightOffsets = new Array(8);
  50108. 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);
  50109. this.brightPassPostProcess.onApply = function (effect) {
  50110. var sU = (1.0 / _this.brightPassPostProcess.width);
  50111. var sV = (1.0 / _this.brightPassPostProcess.height);
  50112. brightOffsets[0] = -0.5 * sU;
  50113. brightOffsets[1] = 0.5 * sV;
  50114. brightOffsets[2] = 0.5 * sU;
  50115. brightOffsets[3] = 0.5 * sV;
  50116. brightOffsets[4] = -0.5 * sU;
  50117. brightOffsets[5] = -0.5 * sV;
  50118. brightOffsets[6] = 0.5 * sU;
  50119. brightOffsets[7] = -0.5 * sV;
  50120. effect.setArray2("dsOffsets", brightOffsets);
  50121. effect.setFloat("brightThreshold", _this.brightThreshold);
  50122. };
  50123. // Add to pipeline
  50124. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  50125. };
  50126. // Create gaussian blur H&V post-processes
  50127. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  50128. var _this = this;
  50129. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  50130. var blurOffsets = new Array(9);
  50131. var blurWeights = new Array(9);
  50132. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  50133. var callback = function (height) {
  50134. return function (effect) {
  50135. // Weights
  50136. var x = 0.0;
  50137. for (var i = 0; i < 9; i++) {
  50138. x = (i - 4.0) / 4.0;
  50139. blurWeights[i] =
  50140. _this.gaussianCoefficient
  50141. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  50142. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  50143. }
  50144. var lastOutputDimensions = {
  50145. width: scene.getEngine().getRenderWidth(),
  50146. height: scene.getEngine().getRenderHeight()
  50147. };
  50148. for (var i = 0; i < 9; i++) {
  50149. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  50150. blurOffsets[i] = value;
  50151. }
  50152. effect.setArray("blurOffsets", blurOffsets);
  50153. effect.setArray("blurWeights", blurWeights);
  50154. if (height) {
  50155. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  50156. }
  50157. else {
  50158. effect.setFloat("blurWidth", _this[blurWidthKey]);
  50159. }
  50160. };
  50161. };
  50162. // Create horizontal gaussian blur post-processes
  50163. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  50164. gaussianBlurHPostProcess.onApply = callback(false);
  50165. // Create vertical gaussian blur post-process
  50166. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  50167. gaussianBlurVPostProcess.onApply = callback(true);
  50168. // Add to pipeline
  50169. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  50170. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  50171. // Finish
  50172. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  50173. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  50174. };
  50175. // Create texture adder post-process
  50176. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  50177. var _this = this;
  50178. 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);
  50179. this.textureAdderPostProcess.onApply = function (effect) {
  50180. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  50181. effect.setTexture("lensSampler", _this.lensTexture);
  50182. effect.setFloat("exposure", _this.exposure);
  50183. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  50184. _this._currentHDRSource = _this.textureAdderFinalPostProcess;
  50185. };
  50186. // Add to pipeline
  50187. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  50188. };
  50189. // Create luminance
  50190. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  50191. var _this = this;
  50192. // Create luminance
  50193. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  50194. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  50195. var offsets = [];
  50196. this.luminancePostProcess.onApply = function (effect) {
  50197. var sU = (1.0 / _this.luminancePostProcess.width);
  50198. var sV = (1.0 / _this.luminancePostProcess.height);
  50199. offsets[0] = -0.5 * sU;
  50200. offsets[1] = 0.5 * sV;
  50201. offsets[2] = 0.5 * sU;
  50202. offsets[3] = 0.5 * sV;
  50203. offsets[4] = -0.5 * sU;
  50204. offsets[5] = -0.5 * sV;
  50205. offsets[6] = 0.5 * sU;
  50206. offsets[7] = -0.5 * sV;
  50207. effect.setArray2("lumOffsets", offsets);
  50208. };
  50209. // Add to pipeline
  50210. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  50211. // Create down sample luminance
  50212. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  50213. var size = Math.pow(3, i);
  50214. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  50215. if (i === 0) {
  50216. defines += "#define FINAL_DOWN_SAMPLER";
  50217. }
  50218. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  50219. this.luminanceDownSamplePostProcesses.push(postProcess);
  50220. }
  50221. // Create callbacks and add effects
  50222. var lastLuminance = this.luminancePostProcess;
  50223. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  50224. var downSampleOffsets = new Array(18);
  50225. pp.onApply = function (effect) {
  50226. var id = 0;
  50227. for (var x = -1; x < 2; x++) {
  50228. for (var y = -1; y < 2; y++) {
  50229. downSampleOffsets[id] = x / lastLuminance.width;
  50230. downSampleOffsets[id + 1] = y / lastLuminance.height;
  50231. id += 2;
  50232. }
  50233. }
  50234. effect.setArray2("dsOffsets", downSampleOffsets);
  50235. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  50236. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  50237. lastLuminance = _this.luminancePostProcess;
  50238. }
  50239. else {
  50240. lastLuminance = pp;
  50241. }
  50242. };
  50243. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  50244. pp.onAfterRender = function (effect) {
  50245. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  50246. 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);
  50247. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  50248. };
  50249. }
  50250. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  50251. });
  50252. };
  50253. // Create HDR post-process
  50254. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  50255. var _this = this;
  50256. 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);
  50257. var outputLiminance = 1;
  50258. var time = 0;
  50259. var lastTime = 0;
  50260. this.hdrPostProcess.onApply = function (effect) {
  50261. effect.setTextureFromPostProcess("textureAdderSampler", _this._bloomEnabled ? _this._currentHDRSource : _this.originalPostProcess);
  50262. time += scene.getEngine().getDeltaTime();
  50263. if (outputLiminance < 0) {
  50264. outputLiminance = _this._hdrCurrentLuminance;
  50265. }
  50266. else {
  50267. var dt = (lastTime - time) / 1000.0;
  50268. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  50269. outputLiminance += _this.hdrDecreaseRate * dt;
  50270. }
  50271. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  50272. outputLiminance -= _this.hdrIncreaseRate * dt;
  50273. }
  50274. else {
  50275. outputLiminance = _this._hdrCurrentLuminance;
  50276. }
  50277. }
  50278. outputLiminance = BABYLON.MathTools.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  50279. effect.setFloat("averageLuminance", outputLiminance);
  50280. lastTime = time;
  50281. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  50282. };
  50283. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  50284. };
  50285. // Create lens flare post-process
  50286. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  50287. var _this = this;
  50288. 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);
  50289. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  50290. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  50291. 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);
  50292. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  50293. var resolution = new BABYLON.Vector2(0, 0);
  50294. // Lens flare
  50295. this.lensFlarePostProcess.onApply = function (effect) {
  50296. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.gaussianBlurHPostProcesses[0] : _this.originalPostProcess);
  50297. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  50298. effect.setFloat("strength", _this.lensFlareStrength);
  50299. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  50300. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  50301. // Shift
  50302. resolution.x = _this.lensFlarePostProcess.width;
  50303. resolution.y = _this.lensFlarePostProcess.height;
  50304. effect.setVector2("resolution", resolution);
  50305. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  50306. };
  50307. // Compose
  50308. 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);
  50309. 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);
  50310. this.lensFlareComposePostProcess.onApply = function (effect) {
  50311. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  50312. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  50313. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  50314. // Lens start rotation matrix
  50315. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  50316. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  50317. 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));
  50318. camRot *= 4.0;
  50319. 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);
  50320. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  50321. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  50322. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  50323. _this._currentHDRSource = _this.lensFlareFinalPostProcess;
  50324. };
  50325. };
  50326. // Create depth-of-field post-process
  50327. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  50328. var _this = this;
  50329. 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);
  50330. this.depthOfFieldPostProcess.onApply = function (effect) {
  50331. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  50332. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  50333. effect.setFloat("distance", _this.depthOfFieldDistance);
  50334. };
  50335. // Add to pipeline
  50336. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  50337. };
  50338. // Create motion blur post-process
  50339. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  50340. var _this = this;
  50341. 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);
  50342. var motionScale = 0;
  50343. var prevViewProjection = BABYLON.Matrix.Identity();
  50344. var invViewProjection = BABYLON.Matrix.Identity();
  50345. var viewProjection = BABYLON.Matrix.Identity();
  50346. var screenSize = BABYLON.Vector2.Zero();
  50347. this.motionBlurPostProcess.onApply = function (effect) {
  50348. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  50349. viewProjection.invertToRef(invViewProjection);
  50350. effect.setMatrix("inverseViewProjection", invViewProjection);
  50351. effect.setMatrix("prevViewProjection", prevViewProjection);
  50352. prevViewProjection = viewProjection;
  50353. screenSize.x = _this.motionBlurPostProcess.width;
  50354. screenSize.y = _this.motionBlurPostProcess.height;
  50355. effect.setVector2("screenSize", screenSize);
  50356. motionScale = scene.getEngine().getFps() / 60.0;
  50357. effect.setFloat("motionScale", motionScale);
  50358. effect.setFloat("motionStrength", _this.motionStrength);
  50359. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  50360. };
  50361. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  50362. };
  50363. // Dispose
  50364. StandardRenderingPipeline.prototype.dispose = function () {
  50365. for (var i = 0; i < this._cameras.length; i++) {
  50366. var camera = this._cameras[i];
  50367. this.originalPostProcess.dispose(camera);
  50368. this.downSampleX4PostProcess.dispose(camera);
  50369. this.brightPassPostProcess.dispose(camera);
  50370. this.textureAdderPostProcess.dispose(camera);
  50371. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  50372. this.gaussianBlurHPostProcesses[j].dispose(camera);
  50373. }
  50374. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  50375. this.gaussianBlurVPostProcesses[j].dispose(camera);
  50376. }
  50377. this.textureAdderFinalPostProcess.dispose(camera);
  50378. this.lensFlarePostProcess.dispose(camera);
  50379. this.lensFlareComposePostProcess.dispose(camera);
  50380. this.depthOfFieldPostProcess.dispose(camera);
  50381. this.motionBlurPostProcess.dispose(camera);
  50382. }
  50383. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  50384. _super.prototype.dispose.call(this);
  50385. };
  50386. // Serialize rendering pipeline
  50387. StandardRenderingPipeline.prototype.serialize = function () {
  50388. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  50389. serializationObject.customType = "StandardRenderingPipeline";
  50390. return serializationObject;
  50391. };
  50392. // Parse serialized pipeline
  50393. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  50394. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  50395. };
  50396. return StandardRenderingPipeline;
  50397. }(BABYLON.PostProcessRenderPipeline));
  50398. // Luminance steps
  50399. StandardRenderingPipeline.LuminanceSteps = 6;
  50400. __decorate([
  50401. BABYLON.serialize()
  50402. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  50403. __decorate([
  50404. BABYLON.serialize()
  50405. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  50406. __decorate([
  50407. BABYLON.serialize()
  50408. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  50409. __decorate([
  50410. BABYLON.serialize()
  50411. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  50412. __decorate([
  50413. BABYLON.serialize()
  50414. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  50415. __decorate([
  50416. BABYLON.serialize()
  50417. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  50418. __decorate([
  50419. BABYLON.serialize()
  50420. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  50421. __decorate([
  50422. BABYLON.serializeAsTexture("lensTexture")
  50423. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  50424. __decorate([
  50425. BABYLON.serialize()
  50426. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  50427. __decorate([
  50428. BABYLON.serialize()
  50429. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  50430. __decorate([
  50431. BABYLON.serialize()
  50432. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  50433. __decorate([
  50434. BABYLON.serializeAsTexture("lensColorTexture")
  50435. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  50436. __decorate([
  50437. BABYLON.serialize()
  50438. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  50439. __decorate([
  50440. BABYLON.serialize()
  50441. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  50442. __decorate([
  50443. BABYLON.serialize()
  50444. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  50445. __decorate([
  50446. BABYLON.serialize()
  50447. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  50448. __decorate([
  50449. BABYLON.serializeAsTexture("lensStarTexture")
  50450. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  50451. __decorate([
  50452. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  50453. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  50454. __decorate([
  50455. BABYLON.serialize()
  50456. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  50457. __decorate([
  50458. BABYLON.serialize()
  50459. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  50460. __decorate([
  50461. BABYLON.serialize()
  50462. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  50463. __decorate([
  50464. BABYLON.serialize()
  50465. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  50466. __decorate([
  50467. BABYLON.serialize()
  50468. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  50469. __decorate([
  50470. BABYLON.serialize()
  50471. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  50472. __decorate([
  50473. BABYLON.serialize()
  50474. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  50475. __decorate([
  50476. BABYLON.serialize()
  50477. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  50478. __decorate([
  50479. BABYLON.serialize()
  50480. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  50481. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  50482. })(BABYLON || (BABYLON = {}));
  50483. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  50484. var BABYLON;
  50485. (function (BABYLON) {
  50486. var FxaaPostProcess = (function (_super) {
  50487. __extends(FxaaPostProcess, _super);
  50488. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50489. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50490. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  50491. _this.onApplyObservable.add(function (effect) {
  50492. var texelSize = _this.texelSize;
  50493. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  50494. });
  50495. return _this;
  50496. }
  50497. return FxaaPostProcess;
  50498. }(BABYLON.PostProcess));
  50499. BABYLON.FxaaPostProcess = FxaaPostProcess;
  50500. })(BABYLON || (BABYLON = {}));
  50501. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  50502. var BABYLON;
  50503. (function (BABYLON) {
  50504. var DefaultRenderingPipeline = (function (_super) {
  50505. __extends(DefaultRenderingPipeline, _super);
  50506. /**
  50507. * @constructor
  50508. * @param {string} name - The rendering pipeline name
  50509. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50510. * @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)
  50511. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50512. */
  50513. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  50514. var _this = _super.call(this, scene.getEngine(), name) || this;
  50515. _this.PassPostProcessId = "PassPostProcessEffect";
  50516. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  50517. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  50518. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  50519. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  50520. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  50521. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  50522. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  50523. // IAnimatable
  50524. _this.animations = [];
  50525. // Values
  50526. _this._bloomEnabled = false;
  50527. _this._fxaaEnabled = false;
  50528. _this._imageProcessingEnabled = true;
  50529. _this._bloomScale = 0.6;
  50530. /**
  50531. * Specifies the size of the bloom blur kernel, relative to the final output size
  50532. */
  50533. _this.bloomKernel = 64;
  50534. /**
  50535. * Specifies the weight of the bloom in the final rendering
  50536. */
  50537. _this._bloomWeight = 0.15;
  50538. _this._cameras = cameras || [];
  50539. // Initialize
  50540. _this._hdr = hdr;
  50541. _this._scene = scene;
  50542. // Misc
  50543. _this._defaultPipelineTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50544. // Attach
  50545. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50546. _this._buildPipeline();
  50547. return _this;
  50548. }
  50549. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  50550. get: function () {
  50551. return this._bloomWeight;
  50552. },
  50553. set: function (value) {
  50554. if (this._bloomWeight === value) {
  50555. return;
  50556. }
  50557. this._bloomWeight = value;
  50558. if (this._hdr && this.copyBack) {
  50559. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  50560. }
  50561. },
  50562. enumerable: true,
  50563. configurable: true
  50564. });
  50565. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  50566. get: function () {
  50567. return this._bloomScale;
  50568. },
  50569. set: function (value) {
  50570. if (this._bloomScale === value) {
  50571. return;
  50572. }
  50573. this._bloomScale = value;
  50574. this._buildPipeline();
  50575. },
  50576. enumerable: true,
  50577. configurable: true
  50578. });
  50579. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  50580. get: function () {
  50581. return this._bloomEnabled;
  50582. },
  50583. set: function (enabled) {
  50584. if (this._bloomEnabled === enabled) {
  50585. return;
  50586. }
  50587. this._bloomEnabled = enabled;
  50588. this._buildPipeline();
  50589. },
  50590. enumerable: true,
  50591. configurable: true
  50592. });
  50593. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  50594. get: function () {
  50595. return this._fxaaEnabled;
  50596. },
  50597. set: function (enabled) {
  50598. if (this._fxaaEnabled === enabled) {
  50599. return;
  50600. }
  50601. this._fxaaEnabled = enabled;
  50602. this._buildPipeline();
  50603. },
  50604. enumerable: true,
  50605. configurable: true
  50606. });
  50607. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  50608. get: function () {
  50609. return this._imageProcessingEnabled;
  50610. },
  50611. set: function (enabled) {
  50612. if (this._imageProcessingEnabled === enabled) {
  50613. return;
  50614. }
  50615. this._imageProcessingEnabled = enabled;
  50616. this._buildPipeline();
  50617. },
  50618. enumerable: true,
  50619. configurable: true
  50620. });
  50621. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  50622. var _this = this;
  50623. var engine = this._scene.getEngine();
  50624. this._disposePostProcesses();
  50625. this._reset();
  50626. if (this.bloomEnabled) {
  50627. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50628. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  50629. if (!this._hdr) {
  50630. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50631. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  50632. this.highlights.autoClear = false;
  50633. this.highlights.alwaysForcePOT = true;
  50634. }
  50635. 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);
  50636. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  50637. this.blurX.alwaysForcePOT = true;
  50638. this.blurX.autoClear = false;
  50639. this.blurX.onActivateObservable.add(function () {
  50640. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  50641. _this.blurX.kernel = _this.bloomKernel * dw;
  50642. });
  50643. 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);
  50644. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  50645. this.blurY.alwaysForcePOT = true;
  50646. this.blurY.autoClear = false;
  50647. this.blurY.onActivateObservable.add(function () {
  50648. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  50649. _this.blurY.kernel = _this.bloomKernel * dh;
  50650. });
  50651. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50652. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  50653. this.copyBack.alwaysForcePOT = true;
  50654. if (this._hdr) {
  50655. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  50656. var w = this.bloomWeight;
  50657. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  50658. }
  50659. else {
  50660. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  50661. }
  50662. this.copyBack.autoClear = false;
  50663. }
  50664. if (this._imageProcessingEnabled) {
  50665. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50666. if (this._hdr) {
  50667. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  50668. }
  50669. }
  50670. if (this.fxaaEnabled) {
  50671. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50672. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  50673. this.fxaa.autoClear = !this.bloomEnabled && !this.imageProcessing;
  50674. }
  50675. else {
  50676. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50677. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  50678. this.finalMerge.autoClear = !this.bloomEnabled && !this.imageProcessing;
  50679. }
  50680. if (this.bloomEnabled) {
  50681. if (this._hdr) {
  50682. this.copyBack.shareOutputWith(this.blurX);
  50683. if (this.imageProcessing) {
  50684. this.imageProcessing.shareOutputWith(this.pass);
  50685. this.imageProcessing.autoClear = false;
  50686. }
  50687. else if (this.fxaa) {
  50688. this.fxaa.shareOutputWith(this.pass);
  50689. }
  50690. else {
  50691. this.finalMerge.shareOutputWith(this.pass);
  50692. }
  50693. }
  50694. else {
  50695. if (this.fxaa) {
  50696. this.fxaa.shareOutputWith(this.pass);
  50697. }
  50698. else {
  50699. this.finalMerge.shareOutputWith(this.pass);
  50700. }
  50701. }
  50702. }
  50703. if (this._cameras !== null) {
  50704. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  50705. }
  50706. };
  50707. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  50708. for (var i = 0; i < this._cameras.length; i++) {
  50709. var camera = this._cameras[i];
  50710. if (this.pass) {
  50711. this.pass.dispose(camera);
  50712. this.pass = null;
  50713. }
  50714. if (this.highlights) {
  50715. this.highlights.dispose(camera);
  50716. this.highlights = null;
  50717. }
  50718. if (this.blurX) {
  50719. this.blurX.dispose(camera);
  50720. this.blurX = null;
  50721. }
  50722. if (this.blurY) {
  50723. this.blurY.dispose(camera);
  50724. this.blurY = null;
  50725. }
  50726. if (this.copyBack) {
  50727. this.copyBack.dispose(camera);
  50728. this.copyBack = null;
  50729. }
  50730. if (this.imageProcessing) {
  50731. this.imageProcessing.dispose(camera);
  50732. this.imageProcessing = null;
  50733. }
  50734. if (this.fxaa) {
  50735. this.fxaa.dispose(camera);
  50736. this.fxaa = null;
  50737. }
  50738. if (this.finalMerge) {
  50739. this.finalMerge.dispose(camera);
  50740. this.finalMerge = null;
  50741. }
  50742. }
  50743. };
  50744. // Dispose
  50745. DefaultRenderingPipeline.prototype.dispose = function () {
  50746. this._disposePostProcesses();
  50747. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  50748. _super.prototype.dispose.call(this);
  50749. };
  50750. // Serialize rendering pipeline
  50751. DefaultRenderingPipeline.prototype.serialize = function () {
  50752. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  50753. serializationObject.customType = "DefaultRenderingPipeline";
  50754. return serializationObject;
  50755. };
  50756. // Parse serialized pipeline
  50757. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  50758. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  50759. };
  50760. return DefaultRenderingPipeline;
  50761. }(BABYLON.PostProcessRenderPipeline));
  50762. __decorate([
  50763. BABYLON.serialize()
  50764. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  50765. __decorate([
  50766. BABYLON.serialize()
  50767. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  50768. __decorate([
  50769. BABYLON.serialize()
  50770. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  50771. __decorate([
  50772. BABYLON.serialize()
  50773. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  50774. __decorate([
  50775. BABYLON.serialize()
  50776. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  50777. __decorate([
  50778. BABYLON.serialize()
  50779. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  50780. __decorate([
  50781. BABYLON.serialize()
  50782. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  50783. __decorate([
  50784. BABYLON.serialize()
  50785. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  50786. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  50787. })(BABYLON || (BABYLON = {}));
  50788. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  50789. var BABYLON;
  50790. (function (BABYLON) {
  50791. var GeometryBufferRenderer = (function () {
  50792. function GeometryBufferRenderer(scene, ratio) {
  50793. if (ratio === void 0) { ratio = 1; }
  50794. var _this = this;
  50795. this._viewMatrix = BABYLON.Matrix.Zero();
  50796. this._projectionMatrix = BABYLON.Matrix.Zero();
  50797. this._transformMatrix = BABYLON.Matrix.Zero();
  50798. this._worldViewProjection = BABYLON.Matrix.Zero();
  50799. this._scene = scene;
  50800. var engine = scene.getEngine();
  50801. // Render target
  50802. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, 2, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  50803. if (!this.isSupported) {
  50804. return null;
  50805. }
  50806. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50807. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50808. this._multiRenderTarget.refreshRate = 1;
  50809. this._multiRenderTarget.renderParticles = false;
  50810. this._multiRenderTarget.renderList = null;
  50811. // set default depth value to 1.0 (far away)
  50812. this._multiRenderTarget.onClearObservable.add(function (engine) {
  50813. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  50814. });
  50815. // Custom render function
  50816. var renderSubMesh = function (subMesh) {
  50817. var mesh = subMesh.getRenderingMesh();
  50818. var scene = _this._scene;
  50819. var engine = scene.getEngine();
  50820. // Culling
  50821. engine.setState(subMesh.getMaterial().backFaceCulling);
  50822. // Managing instances
  50823. var batch = mesh._getInstancesRenderList(subMesh._id);
  50824. if (batch.mustReturn) {
  50825. return;
  50826. }
  50827. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  50828. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  50829. engine.enableEffect(_this._effect);
  50830. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  50831. var material = subMesh.getMaterial();
  50832. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50833. _this._effect.setMatrix("view", scene.getViewMatrix());
  50834. // Alpha test
  50835. if (material && material.needAlphaTesting()) {
  50836. var alphaTexture = material.getAlphaTestTexture();
  50837. _this._effect.setTexture("diffuseSampler", alphaTexture);
  50838. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50839. }
  50840. // Bones
  50841. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50842. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50843. }
  50844. // Draw
  50845. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  50846. }
  50847. };
  50848. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  50849. var index;
  50850. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50851. renderSubMesh(opaqueSubMeshes.data[index]);
  50852. }
  50853. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50854. renderSubMesh(alphaTestSubMeshes.data[index]);
  50855. }
  50856. };
  50857. }
  50858. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  50859. set: function (meshes) {
  50860. this._multiRenderTarget.renderList = meshes;
  50861. },
  50862. enumerable: true,
  50863. configurable: true
  50864. });
  50865. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  50866. get: function () {
  50867. return this._multiRenderTarget.isSupported;
  50868. },
  50869. enumerable: true,
  50870. configurable: true
  50871. });
  50872. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  50873. var material = subMesh.getMaterial();
  50874. if (material && material.disableDepthWrite) {
  50875. return false;
  50876. }
  50877. var defines = [];
  50878. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  50879. var mesh = subMesh.getMesh();
  50880. var scene = mesh.getScene();
  50881. // Alpha test
  50882. if (material && material.needAlphaTesting()) {
  50883. defines.push("#define ALPHATEST");
  50884. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50885. attribs.push(BABYLON.VertexBuffer.UVKind);
  50886. defines.push("#define UV1");
  50887. }
  50888. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50889. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50890. defines.push("#define UV2");
  50891. }
  50892. }
  50893. // Bones
  50894. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50895. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50896. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50897. if (mesh.numBoneInfluencers > 4) {
  50898. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50899. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50900. }
  50901. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50902. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50903. }
  50904. else {
  50905. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50906. }
  50907. // Instances
  50908. if (useInstances) {
  50909. defines.push("#define INSTANCES");
  50910. attribs.push("world0");
  50911. attribs.push("world1");
  50912. attribs.push("world2");
  50913. attribs.push("world3");
  50914. }
  50915. // Get correct effect
  50916. var join = defines.join("\n");
  50917. if (this._cachedDefines !== join) {
  50918. this._cachedDefines = join;
  50919. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  50920. }
  50921. return this._effect.isReady();
  50922. };
  50923. GeometryBufferRenderer.prototype.getGBuffer = function () {
  50924. return this._multiRenderTarget;
  50925. };
  50926. // Methods
  50927. GeometryBufferRenderer.prototype.dispose = function () {
  50928. this.getGBuffer().dispose();
  50929. };
  50930. return GeometryBufferRenderer;
  50931. }());
  50932. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  50933. })(BABYLON || (BABYLON = {}));
  50934. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  50935. var BABYLON;
  50936. (function (BABYLON) {
  50937. var RefractionPostProcess = (function (_super) {
  50938. __extends(RefractionPostProcess, _super);
  50939. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  50940. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  50941. _this.color = color;
  50942. _this.depth = depth;
  50943. _this.colorLevel = colorLevel;
  50944. _this.onActivateObservable.add(function (cam) {
  50945. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  50946. });
  50947. _this.onApplyObservable.add(function (effect) {
  50948. effect.setColor3("baseColor", _this.color);
  50949. effect.setFloat("depth", _this.depth);
  50950. effect.setFloat("colorLevel", _this.colorLevel);
  50951. effect.setTexture("refractionSampler", _this._refRexture);
  50952. });
  50953. return _this;
  50954. }
  50955. // Methods
  50956. RefractionPostProcess.prototype.dispose = function (camera) {
  50957. if (this._refRexture) {
  50958. this._refRexture.dispose();
  50959. }
  50960. _super.prototype.dispose.call(this, camera);
  50961. };
  50962. return RefractionPostProcess;
  50963. }(BABYLON.PostProcess));
  50964. BABYLON.RefractionPostProcess = RefractionPostProcess;
  50965. })(BABYLON || (BABYLON = {}));
  50966. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  50967. var BABYLON;
  50968. (function (BABYLON) {
  50969. var BlackAndWhitePostProcess = (function (_super) {
  50970. __extends(BlackAndWhitePostProcess, _super);
  50971. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  50972. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  50973. _this.degree = 1;
  50974. _this.onApplyObservable.add(function (effect) {
  50975. effect.setFloat("degree", _this.degree);
  50976. });
  50977. return _this;
  50978. }
  50979. return BlackAndWhitePostProcess;
  50980. }(BABYLON.PostProcess));
  50981. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  50982. })(BABYLON || (BABYLON = {}));
  50983. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  50984. var BABYLON;
  50985. (function (BABYLON) {
  50986. var ConvolutionPostProcess = (function (_super) {
  50987. __extends(ConvolutionPostProcess, _super);
  50988. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  50989. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  50990. _this.kernel = kernel;
  50991. _this.onApply = function (effect) {
  50992. effect.setFloat2("screenSize", _this.width, _this.height);
  50993. effect.setArray("kernel", _this.kernel);
  50994. };
  50995. return _this;
  50996. }
  50997. return ConvolutionPostProcess;
  50998. }(BABYLON.PostProcess));
  50999. // Statics
  51000. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  51001. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  51002. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  51003. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  51004. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  51005. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  51006. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  51007. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  51008. })(BABYLON || (BABYLON = {}));
  51009. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  51010. var BABYLON;
  51011. (function (BABYLON) {
  51012. var FilterPostProcess = (function (_super) {
  51013. __extends(FilterPostProcess, _super);
  51014. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  51015. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  51016. _this.kernelMatrix = kernelMatrix;
  51017. _this.onApply = function (effect) {
  51018. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  51019. };
  51020. return _this;
  51021. }
  51022. return FilterPostProcess;
  51023. }(BABYLON.PostProcess));
  51024. BABYLON.FilterPostProcess = FilterPostProcess;
  51025. })(BABYLON || (BABYLON = {}));
  51026. //# sourceMappingURL=babylon.filterPostProcess.js.map
  51027. var BABYLON;
  51028. (function (BABYLON) {
  51029. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  51030. var VolumetricLightScatteringPostProcess = (function (_super) {
  51031. __extends(VolumetricLightScatteringPostProcess, _super);
  51032. /**
  51033. * @constructor
  51034. * @param {string} name - The post-process name
  51035. * @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)
  51036. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  51037. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  51038. * @param {number} samples - The post-process quality, default 100
  51039. * @param {number} samplingMode - The post-process filtering mode
  51040. * @param {BABYLON.Engine} engine - The babylon engine
  51041. * @param {boolean} reusable - If the post-process is reusable
  51042. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  51043. */
  51044. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  51045. if (samples === void 0) { samples = 100; }
  51046. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51047. 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;
  51048. _this._screenCoordinates = BABYLON.Vector2.Zero();
  51049. /**
  51050. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  51051. * @type {Vector3}
  51052. */
  51053. _this.customMeshPosition = BABYLON.Vector3.Zero();
  51054. /**
  51055. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  51056. * @type {boolean}
  51057. */
  51058. _this.useCustomMeshPosition = false;
  51059. /**
  51060. * If the post-process should inverse the light scattering direction
  51061. * @type {boolean}
  51062. */
  51063. _this.invert = true;
  51064. /**
  51065. * Array containing the excluded meshes not rendered in the internal pass
  51066. */
  51067. _this.excludedMeshes = new Array();
  51068. /**
  51069. * Controls the overall intensity of the post-process
  51070. * @type {number}
  51071. */
  51072. _this.exposure = 0.3;
  51073. /**
  51074. * Dissipates each sample's contribution in range [0, 1]
  51075. * @type {number}
  51076. */
  51077. _this.decay = 0.96815;
  51078. /**
  51079. * Controls the overall intensity of each sample
  51080. * @type {number}
  51081. */
  51082. _this.weight = 0.58767;
  51083. /**
  51084. * Controls the density of each sample
  51085. * @type {number}
  51086. */
  51087. _this.density = 0.926;
  51088. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  51089. var engine = scene.getEngine();
  51090. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  51091. // Configure mesh
  51092. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  51093. // Configure
  51094. _this._createPass(scene, ratio.passRatio || ratio);
  51095. _this.onActivate = function (camera) {
  51096. if (!_this.isSupported) {
  51097. _this.dispose(camera);
  51098. }
  51099. _this.onActivate = null;
  51100. };
  51101. _this.onApplyObservable.add(function (effect) {
  51102. _this._updateMeshScreenCoordinates(scene);
  51103. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  51104. effect.setFloat("exposure", _this.exposure);
  51105. effect.setFloat("decay", _this.decay);
  51106. effect.setFloat("weight", _this.weight);
  51107. effect.setFloat("density", _this.density);
  51108. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  51109. });
  51110. return _this;
  51111. }
  51112. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  51113. get: function () {
  51114. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51115. return false;
  51116. },
  51117. set: function (useDiffuseColor) {
  51118. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51119. },
  51120. enumerable: true,
  51121. configurable: true
  51122. });
  51123. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  51124. var mesh = subMesh.getMesh();
  51125. // Render this.mesh as default
  51126. if (mesh === this.mesh) {
  51127. return mesh.material.isReady(mesh);
  51128. }
  51129. var defines = [];
  51130. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51131. var material = subMesh.getMaterial();
  51132. var needUV = false;
  51133. // Alpha test
  51134. if (material) {
  51135. if (material.needAlphaTesting()) {
  51136. defines.push("#define ALPHATEST");
  51137. }
  51138. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51139. attribs.push(BABYLON.VertexBuffer.UVKind);
  51140. defines.push("#define UV1");
  51141. }
  51142. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51143. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51144. defines.push("#define UV2");
  51145. }
  51146. }
  51147. // Bones
  51148. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51149. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51150. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51151. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51152. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51153. }
  51154. else {
  51155. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51156. }
  51157. // Instances
  51158. if (useInstances) {
  51159. defines.push("#define INSTANCES");
  51160. attribs.push("world0");
  51161. attribs.push("world1");
  51162. attribs.push("world2");
  51163. attribs.push("world3");
  51164. }
  51165. // Get correct effect
  51166. var join = defines.join("\n");
  51167. if (this._cachedDefines !== join) {
  51168. this._cachedDefines = join;
  51169. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  51170. }
  51171. return this._volumetricLightScatteringPass.isReady();
  51172. };
  51173. /**
  51174. * Sets the new light position for light scattering effect
  51175. * @param {BABYLON.Vector3} The new custom light position
  51176. */
  51177. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  51178. this.customMeshPosition = position;
  51179. };
  51180. /**
  51181. * Returns the light position for light scattering effect
  51182. * @return {BABYLON.Vector3} The custom light position
  51183. */
  51184. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  51185. return this.customMeshPosition;
  51186. };
  51187. /**
  51188. * Disposes the internal assets and detaches the post-process from the camera
  51189. */
  51190. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  51191. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  51192. if (rttIndex !== -1) {
  51193. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  51194. }
  51195. this._volumetricLightScatteringRTT.dispose();
  51196. _super.prototype.dispose.call(this, camera);
  51197. };
  51198. /**
  51199. * Returns the render target texture used by the post-process
  51200. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  51201. */
  51202. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  51203. return this._volumetricLightScatteringRTT;
  51204. };
  51205. // Private methods
  51206. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  51207. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  51208. return true;
  51209. }
  51210. return false;
  51211. };
  51212. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  51213. var _this = this;
  51214. var engine = scene.getEngine();
  51215. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  51216. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51217. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51218. this._volumetricLightScatteringRTT.renderList = null;
  51219. this._volumetricLightScatteringRTT.renderParticles = false;
  51220. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  51221. // Custom render function for submeshes
  51222. var renderSubMesh = function (subMesh) {
  51223. var mesh = subMesh.getRenderingMesh();
  51224. if (_this._meshExcluded(mesh)) {
  51225. return;
  51226. }
  51227. var scene = mesh.getScene();
  51228. var engine = scene.getEngine();
  51229. // Culling
  51230. engine.setState(subMesh.getMaterial().backFaceCulling);
  51231. // Managing instances
  51232. var batch = mesh._getInstancesRenderList(subMesh._id);
  51233. if (batch.mustReturn) {
  51234. return;
  51235. }
  51236. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  51237. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  51238. var effect = _this._volumetricLightScatteringPass;
  51239. if (mesh === _this.mesh) {
  51240. if (subMesh.effect) {
  51241. effect = subMesh.effect;
  51242. }
  51243. else {
  51244. effect = subMesh.getMaterial().getEffect();
  51245. }
  51246. }
  51247. engine.enableEffect(effect);
  51248. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  51249. if (mesh === _this.mesh) {
  51250. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  51251. }
  51252. else {
  51253. var material = subMesh.getMaterial();
  51254. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  51255. // Alpha test
  51256. if (material && material.needAlphaTesting()) {
  51257. var alphaTexture = material.getAlphaTestTexture();
  51258. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  51259. if (alphaTexture) {
  51260. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51261. }
  51262. }
  51263. // Bones
  51264. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51265. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51266. }
  51267. }
  51268. // Draw
  51269. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  51270. }
  51271. };
  51272. // Render target texture callbacks
  51273. var savedSceneClearColor;
  51274. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  51275. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  51276. savedSceneClearColor = scene.clearColor;
  51277. scene.clearColor = sceneClearColor;
  51278. });
  51279. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  51280. scene.clearColor = savedSceneClearColor;
  51281. });
  51282. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  51283. var engine = scene.getEngine();
  51284. var index;
  51285. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51286. renderSubMesh(opaqueSubMeshes.data[index]);
  51287. }
  51288. engine.setAlphaTesting(true);
  51289. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51290. renderSubMesh(alphaTestSubMeshes.data[index]);
  51291. }
  51292. engine.setAlphaTesting(false);
  51293. if (transparentSubMeshes.length) {
  51294. // Sort sub meshes
  51295. for (index = 0; index < transparentSubMeshes.length; index++) {
  51296. var submesh = transparentSubMeshes.data[index];
  51297. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  51298. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  51299. }
  51300. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  51301. sortedArray.sort(function (a, b) {
  51302. // Alpha index first
  51303. if (a._alphaIndex > b._alphaIndex) {
  51304. return 1;
  51305. }
  51306. if (a._alphaIndex < b._alphaIndex) {
  51307. return -1;
  51308. }
  51309. // Then distance to camera
  51310. if (a._distanceToCamera < b._distanceToCamera) {
  51311. return 1;
  51312. }
  51313. if (a._distanceToCamera > b._distanceToCamera) {
  51314. return -1;
  51315. }
  51316. return 0;
  51317. });
  51318. // Render sub meshes
  51319. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51320. for (index = 0; index < sortedArray.length; index++) {
  51321. renderSubMesh(sortedArray[index]);
  51322. }
  51323. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51324. }
  51325. };
  51326. };
  51327. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  51328. var transform = scene.getTransformMatrix();
  51329. var meshPosition;
  51330. if (this.useCustomMeshPosition) {
  51331. meshPosition = this.customMeshPosition;
  51332. }
  51333. else if (this.attachedNode) {
  51334. meshPosition = this.attachedNode.position;
  51335. }
  51336. else {
  51337. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  51338. }
  51339. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  51340. this._screenCoordinates.x = pos.x / this._viewPort.width;
  51341. this._screenCoordinates.y = pos.y / this._viewPort.height;
  51342. if (this.invert)
  51343. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  51344. };
  51345. // Static methods
  51346. /**
  51347. * Creates a default mesh for the Volumeric Light Scattering post-process
  51348. * @param {string} The mesh name
  51349. * @param {BABYLON.Scene} The scene where to create the mesh
  51350. * @return {BABYLON.Mesh} the default mesh
  51351. */
  51352. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  51353. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  51354. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  51355. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  51356. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  51357. mesh.material = material;
  51358. return mesh;
  51359. };
  51360. return VolumetricLightScatteringPostProcess;
  51361. }(BABYLON.PostProcess));
  51362. __decorate([
  51363. BABYLON.serializeAsVector3()
  51364. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  51365. __decorate([
  51366. BABYLON.serialize()
  51367. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  51368. __decorate([
  51369. BABYLON.serialize()
  51370. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  51371. __decorate([
  51372. BABYLON.serializeAsMeshReference()
  51373. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  51374. __decorate([
  51375. BABYLON.serialize()
  51376. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  51377. __decorate([
  51378. BABYLON.serialize()
  51379. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  51380. __decorate([
  51381. BABYLON.serialize()
  51382. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  51383. __decorate([
  51384. BABYLON.serialize()
  51385. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  51386. __decorate([
  51387. BABYLON.serialize()
  51388. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  51389. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  51390. })(BABYLON || (BABYLON = {}));
  51391. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  51392. //
  51393. // This post-process allows the modification of rendered colors by using
  51394. // a 'look-up table' (LUT). This effect is also called Color Grading.
  51395. //
  51396. // The object needs to be provided an url to a texture containing the color
  51397. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  51398. // Use an image editing software to tweak the LUT to match your needs.
  51399. //
  51400. // For an example of a color LUT, see here:
  51401. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  51402. // For explanations on color grading, see here:
  51403. // http://udn.epicgames.com/Three/ColorGrading.html
  51404. //
  51405. var BABYLON;
  51406. (function (BABYLON) {
  51407. var ColorCorrectionPostProcess = (function (_super) {
  51408. __extends(ColorCorrectionPostProcess, _super);
  51409. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  51410. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  51411. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  51412. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  51413. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51414. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51415. _this.onApply = function (effect) {
  51416. effect.setTexture("colorTable", _this._colorTableTexture);
  51417. };
  51418. return _this;
  51419. }
  51420. return ColorCorrectionPostProcess;
  51421. }(BABYLON.PostProcess));
  51422. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  51423. })(BABYLON || (BABYLON = {}));
  51424. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  51425. var BABYLON;
  51426. (function (BABYLON) {
  51427. var TonemappingOperator;
  51428. (function (TonemappingOperator) {
  51429. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  51430. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  51431. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  51432. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  51433. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  51434. ;
  51435. var TonemapPostProcess = (function (_super) {
  51436. __extends(TonemapPostProcess, _super);
  51437. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  51438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51439. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51440. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  51441. _this._operator = _operator;
  51442. _this.exposureAdjustment = exposureAdjustment;
  51443. var defines = "#define ";
  51444. if (_this._operator === TonemappingOperator.Hable)
  51445. defines += "HABLE_TONEMAPPING";
  51446. else if (_this._operator === TonemappingOperator.Reinhard)
  51447. defines += "REINHARD_TONEMAPPING";
  51448. else if (_this._operator === TonemappingOperator.HejiDawson)
  51449. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  51450. else if (_this._operator === TonemappingOperator.Photographic)
  51451. defines += "PHOTOGRAPHIC_TONEMAPPING";
  51452. //sadly a second call to create the effect.
  51453. _this.updateEffect(defines);
  51454. _this.onApply = function (effect) {
  51455. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  51456. };
  51457. return _this;
  51458. }
  51459. return TonemapPostProcess;
  51460. }(BABYLON.PostProcess));
  51461. BABYLON.TonemapPostProcess = TonemapPostProcess;
  51462. })(BABYLON || (BABYLON = {}));
  51463. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  51464. var BABYLON;
  51465. (function (BABYLON) {
  51466. var DisplayPassPostProcess = (function (_super) {
  51467. __extends(DisplayPassPostProcess, _super);
  51468. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  51469. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  51470. }
  51471. return DisplayPassPostProcess;
  51472. }(BABYLON.PostProcess));
  51473. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  51474. })(BABYLON || (BABYLON = {}));
  51475. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  51476. var BABYLON;
  51477. (function (BABYLON) {
  51478. var HighlightsPostProcess = (function (_super) {
  51479. __extends(HighlightsPostProcess, _super);
  51480. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51481. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51482. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  51483. }
  51484. return HighlightsPostProcess;
  51485. }(BABYLON.PostProcess));
  51486. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  51487. })(BABYLON || (BABYLON = {}));
  51488. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  51489. var BABYLON;
  51490. (function (BABYLON) {
  51491. var ImageProcessingPostProcess = (function (_super) {
  51492. __extends(ImageProcessingPostProcess, _super);
  51493. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51494. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51495. var _this = _super.call(this, name, "imageProcessing", [
  51496. 'contrast',
  51497. 'vignetteSettings1',
  51498. 'vignetteSettings2',
  51499. 'cameraExposureLinear',
  51500. 'vCameraColorCurveNegative',
  51501. 'vCameraColorCurveNeutral',
  51502. 'vCameraColorCurvePositive',
  51503. 'colorTransformSettings'
  51504. ], ["txColorTransform"], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  51505. _this.colorGradingWeight = 1.0;
  51506. _this.colorCurves = new BABYLON.ColorCurves();
  51507. _this._colorCurvesEnabled = true;
  51508. _this.cameraFov = 0.5;
  51509. _this.vignetteStretch = 0;
  51510. _this.vignetteCentreX = 0;
  51511. _this.vignetteCentreY = 0;
  51512. _this.vignetteWeight = 1.5;
  51513. _this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  51514. _this._vignetteBlendMode = ImageProcessingPostProcess.VIGNETTEMODE_MULTIPLY;
  51515. _this._vignetteEnabled = true;
  51516. _this.cameraContrast = 1.0;
  51517. _this.cameraExposure = 1.68;
  51518. _this._cameraToneMappingEnabled = true;
  51519. _this._fromLinearSpace = false;
  51520. _this._updateParameters();
  51521. _this.onApply = function (effect) {
  51522. var aspectRatio = _this.aspectRatio;
  51523. // Color
  51524. if (_this._colorCurvesEnabled) {
  51525. BABYLON.ColorCurves.Bind(_this.colorCurves, effect);
  51526. }
  51527. if (_this._vignetteEnabled) {
  51528. // Vignette
  51529. var vignetteScaleY = Math.tan(_this.cameraFov * 0.5);
  51530. var vignetteScaleX = vignetteScaleY * aspectRatio;
  51531. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  51532. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, _this.vignetteStretch);
  51533. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, _this.vignetteStretch);
  51534. effect.setFloat4('vignetteSettings1', vignetteScaleX, vignetteScaleY, -vignetteScaleX * _this.vignetteCentreX, -vignetteScaleY * _this.vignetteCentreY);
  51535. var vignettePower = -2.0 * _this.vignetteWeight;
  51536. effect.setFloat4('vignetteSettings2', _this.vignetteColor.r, _this.vignetteColor.g, _this.vignetteColor.b, vignettePower);
  51537. }
  51538. // Contrast and exposure
  51539. effect.setFloat('contrast', _this.cameraContrast);
  51540. effect.setFloat('cameraExposureLinear', Math.pow(2.0, -_this.cameraExposure) * Math.PI);
  51541. // Color transform settings
  51542. if (_this._colorGradingTexture) {
  51543. effect.setTexture('txColorTransform', _this.colorGradingTexture);
  51544. var textureSize = _this.colorGradingTexture.getSize().height;
  51545. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  51546. 0.5 / textureSize, // textureOffset
  51547. textureSize, // textureSize
  51548. _this.colorGradingWeight // weight
  51549. );
  51550. }
  51551. };
  51552. return _this;
  51553. }
  51554. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  51555. get: function () {
  51556. return this._colorGradingTexture;
  51557. },
  51558. set: function (value) {
  51559. if (this._colorGradingTexture === value) {
  51560. return;
  51561. }
  51562. this._colorGradingTexture = value;
  51563. this._updateParameters();
  51564. },
  51565. enumerable: true,
  51566. configurable: true
  51567. });
  51568. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  51569. get: function () {
  51570. return this._vignetteBlendMode;
  51571. },
  51572. set: function (value) {
  51573. if (this._vignetteBlendMode === value) {
  51574. return;
  51575. }
  51576. this._vignetteBlendMode = value;
  51577. this._updateParameters();
  51578. },
  51579. enumerable: true,
  51580. configurable: true
  51581. });
  51582. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  51583. get: function () {
  51584. return this._colorCurvesEnabled;
  51585. },
  51586. set: function (value) {
  51587. if (this._colorCurvesEnabled === value) {
  51588. return;
  51589. }
  51590. this._colorCurvesEnabled = value;
  51591. this._updateParameters();
  51592. },
  51593. enumerable: true,
  51594. configurable: true
  51595. });
  51596. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  51597. get: function () {
  51598. return this._vignetteEnabled;
  51599. },
  51600. set: function (value) {
  51601. if (this._vignetteEnabled === value) {
  51602. return;
  51603. }
  51604. this._vignetteEnabled = value;
  51605. this._updateParameters();
  51606. },
  51607. enumerable: true,
  51608. configurable: true
  51609. });
  51610. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  51611. get: function () {
  51612. return this._fromLinearSpace;
  51613. },
  51614. set: function (value) {
  51615. if (this._fromLinearSpace === value) {
  51616. return;
  51617. }
  51618. this._fromLinearSpace = value;
  51619. this._updateParameters();
  51620. },
  51621. enumerable: true,
  51622. configurable: true
  51623. });
  51624. Object.defineProperty(ImageProcessingPostProcess.prototype, "cameraToneMappingEnabled", {
  51625. get: function () {
  51626. return this._cameraToneMappingEnabled;
  51627. },
  51628. set: function (value) {
  51629. if (this._cameraToneMappingEnabled === value) {
  51630. return;
  51631. }
  51632. this._cameraToneMappingEnabled = value;
  51633. this._updateParameters();
  51634. },
  51635. enumerable: true,
  51636. configurable: true
  51637. });
  51638. ImageProcessingPostProcess.prototype._updateParameters = function () {
  51639. var defines = "";
  51640. var samplers = ["textureSampler"];
  51641. if (this.colorGradingTexture) {
  51642. defines = "#define COLORGRADING\r\n";
  51643. samplers.push("txColorTransform");
  51644. }
  51645. if (this._vignetteEnabled) {
  51646. defines += "#define VIGNETTE\r\n";
  51647. if (this.vignetteBlendMode === ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY) {
  51648. defines += "#define VIGNETTEBLENDMODEMULTIPLY\r\n";
  51649. }
  51650. else {
  51651. defines += "#define VIGNETTEBLENDMODEOPAQUE\r\n";
  51652. }
  51653. }
  51654. if (this.cameraToneMappingEnabled) {
  51655. defines += "#define TONEMAPPING\r\n";
  51656. }
  51657. if (this._colorCurvesEnabled && this.colorCurves) {
  51658. defines += "#define COLORCURVES\r\n";
  51659. }
  51660. if (this._fromLinearSpace) {
  51661. defines += "#define FROMLINEARSPACE\r\n";
  51662. }
  51663. this.updateEffect(defines, null, samplers);
  51664. };
  51665. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_MULTIPLY", {
  51666. get: function () {
  51667. return ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY;
  51668. },
  51669. enumerable: true,
  51670. configurable: true
  51671. });
  51672. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_OPAQUE", {
  51673. get: function () {
  51674. return ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE;
  51675. },
  51676. enumerable: true,
  51677. configurable: true
  51678. });
  51679. return ImageProcessingPostProcess;
  51680. }(BABYLON.PostProcess));
  51681. // Statics
  51682. ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY = 0;
  51683. ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE = 1;
  51684. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  51685. })(BABYLON || (BABYLON = {}));
  51686. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  51687. var BABYLON;
  51688. (function (BABYLON) {
  51689. var BlurPostProcess = (function (_super) {
  51690. __extends(BlurPostProcess, _super);
  51691. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  51692. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51693. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51694. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  51695. _this.direction = direction;
  51696. _this.onApplyObservable.add(function (effect) {
  51697. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  51698. });
  51699. _this.kernel = kernel;
  51700. return _this;
  51701. }
  51702. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  51703. /**
  51704. * Gets the length in pixels of the blur sample region
  51705. */
  51706. get: function () {
  51707. return this._idealKernel;
  51708. },
  51709. /**
  51710. * Sets the length in pixels of the blur sample region
  51711. */
  51712. set: function (v) {
  51713. if (this._idealKernel === v) {
  51714. return;
  51715. }
  51716. v = Math.max(v, 1);
  51717. this._idealKernel = v;
  51718. this._kernel = this._nearestBestKernel(v);
  51719. this._updateParameters();
  51720. },
  51721. enumerable: true,
  51722. configurable: true
  51723. });
  51724. BlurPostProcess.prototype._updateParameters = function () {
  51725. // Generate sampling offsets and weights
  51726. var N = this._kernel;
  51727. var centerIndex = (N - 1) / 2;
  51728. // Generate Gaussian sampling weights over kernel
  51729. var offsets = [];
  51730. var weights = [];
  51731. var totalWeight = 0;
  51732. for (var i = 0; i < N; i++) {
  51733. var u = i / (N - 1);
  51734. var w = this._gaussianWeight(u * 2.0 - 1);
  51735. offsets[i] = (i - centerIndex);
  51736. weights[i] = w;
  51737. totalWeight += w;
  51738. }
  51739. // Normalize weights
  51740. for (var i = 0; i < weights.length; i++) {
  51741. weights[i] /= totalWeight;
  51742. }
  51743. // Optimize: combine samples to take advantage of hardware linear sampling
  51744. // Walk from left to center, combining pairs (symmetrically)
  51745. var linearSamplingWeights = [];
  51746. var linearSamplingOffsets = [];
  51747. var linearSamplingMap = [];
  51748. for (var i = 0; i <= centerIndex; i += 2) {
  51749. var j = Math.min(i + 1, Math.floor(centerIndex));
  51750. var singleCenterSample = i === j;
  51751. if (singleCenterSample) {
  51752. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  51753. }
  51754. else {
  51755. var sharedCell = j === centerIndex;
  51756. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  51757. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  51758. if (offsetLinear === 0) {
  51759. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  51760. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  51761. }
  51762. else {
  51763. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  51764. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  51765. }
  51766. }
  51767. }
  51768. for (var i = 0; i < linearSamplingMap.length; i++) {
  51769. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  51770. linearSamplingWeights[i] = linearSamplingMap[i].w;
  51771. }
  51772. // Replace with optimized
  51773. offsets = linearSamplingOffsets;
  51774. weights = linearSamplingWeights;
  51775. // Generate shaders
  51776. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  51777. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  51778. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  51779. var defines = "";
  51780. for (var i = 0; i < varyingCount; i++) {
  51781. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  51782. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  51783. }
  51784. var depCount = 0;
  51785. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  51786. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  51787. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  51788. depCount++;
  51789. }
  51790. this.updateEffect(defines, null, null, {
  51791. varyingCount: varyingCount,
  51792. depCount: depCount
  51793. });
  51794. };
  51795. /**
  51796. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  51797. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  51798. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  51799. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  51800. * The gaps between physical kernels are compensated for in the weighting of the samples
  51801. * @param idealKernel Ideal blur kernel.
  51802. * @return Nearest best kernel.
  51803. */
  51804. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  51805. var v = Math.round(idealKernel);
  51806. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  51807. var k = _a[_i];
  51808. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  51809. return Math.max(k, 3);
  51810. }
  51811. }
  51812. return Math.max(v, 3);
  51813. };
  51814. /**
  51815. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  51816. * @param x The point on the Gaussian distribution to sample.
  51817. * @return the value of the Gaussian function at x.
  51818. */
  51819. BlurPostProcess.prototype._gaussianWeight = function (x) {
  51820. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  51821. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  51822. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  51823. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  51824. // truncated at around 1.3% of peak strength.
  51825. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  51826. var sigma = (1 / 3);
  51827. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  51828. var exponent = -((x * x) / (2.0 * sigma * sigma));
  51829. var weight = (1.0 / denominator) * Math.exp(exponent);
  51830. return weight;
  51831. };
  51832. /**
  51833. * Generates a string that can be used as a floating point number in GLSL.
  51834. * @param x Value to print.
  51835. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  51836. * @return GLSL float string.
  51837. */
  51838. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  51839. if (decimalFigures === void 0) { decimalFigures = 8; }
  51840. return x.toFixed(decimalFigures).replace(/0+$/, '');
  51841. };
  51842. return BlurPostProcess;
  51843. }(BABYLON.PostProcess));
  51844. BABYLON.BlurPostProcess = BlurPostProcess;
  51845. })(BABYLON || (BABYLON = {}));
  51846. //# sourceMappingURL=babylon.blurPostProcess.js.map
  51847. /// <reference path="..\babylon.node.ts" />
  51848. var BABYLON;
  51849. (function (BABYLON) {
  51850. var Bone = (function (_super) {
  51851. __extends(Bone, _super);
  51852. function Bone(name, skeleton, parentBone, matrix, restPose) {
  51853. var _this = _super.call(this, name, skeleton.getScene()) || this;
  51854. _this.name = name;
  51855. _this.children = new Array();
  51856. _this.animations = new Array();
  51857. _this._worldTransform = new BABYLON.Matrix();
  51858. _this._absoluteTransform = new BABYLON.Matrix();
  51859. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  51860. _this._scaleMatrix = BABYLON.Matrix.Identity();
  51861. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  51862. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  51863. _this._scalingDeterminant = 1;
  51864. _this._skeleton = skeleton;
  51865. _this._localMatrix = matrix;
  51866. _this._baseMatrix = matrix.clone();
  51867. _this._restPose = restPose ? restPose : matrix.clone();
  51868. skeleton.bones.push(_this);
  51869. if (parentBone) {
  51870. _this._parent = parentBone;
  51871. parentBone.children.push(_this);
  51872. }
  51873. else {
  51874. _this._parent = null;
  51875. }
  51876. _this._updateDifferenceMatrix();
  51877. if (_this.getAbsoluteTransform().determinant() < 0) {
  51878. _this._scalingDeterminant *= -1;
  51879. }
  51880. return _this;
  51881. }
  51882. Object.defineProperty(Bone.prototype, "_matrix", {
  51883. get: function () {
  51884. return this._localMatrix;
  51885. },
  51886. set: function (val) {
  51887. if (this._localMatrix) {
  51888. this._localMatrix.copyFrom(val);
  51889. }
  51890. else {
  51891. this._localMatrix = val;
  51892. }
  51893. },
  51894. enumerable: true,
  51895. configurable: true
  51896. });
  51897. // Members
  51898. Bone.prototype.getParent = function () {
  51899. return this._parent;
  51900. };
  51901. Bone.prototype.getLocalMatrix = function () {
  51902. return this._localMatrix;
  51903. };
  51904. Bone.prototype.getBaseMatrix = function () {
  51905. return this._baseMatrix;
  51906. };
  51907. Bone.prototype.getRestPose = function () {
  51908. return this._restPose;
  51909. };
  51910. Bone.prototype.returnToRest = function () {
  51911. this.updateMatrix(this._restPose.clone());
  51912. };
  51913. Bone.prototype.getWorldMatrix = function () {
  51914. return this._worldTransform;
  51915. };
  51916. Bone.prototype.getInvertedAbsoluteTransform = function () {
  51917. return this._invertedAbsoluteTransform;
  51918. };
  51919. Bone.prototype.getAbsoluteTransform = function () {
  51920. return this._absoluteTransform;
  51921. };
  51922. Object.defineProperty(Bone.prototype, "position", {
  51923. // Properties (matches AbstractMesh properties)
  51924. get: function () {
  51925. return this.getPosition();
  51926. },
  51927. set: function (newPosition) {
  51928. this.setPosition(newPosition);
  51929. },
  51930. enumerable: true,
  51931. configurable: true
  51932. });
  51933. Object.defineProperty(Bone.prototype, "rotation", {
  51934. get: function () {
  51935. return this.getRotation();
  51936. },
  51937. set: function (newRotation) {
  51938. this.setRotation(newRotation);
  51939. },
  51940. enumerable: true,
  51941. configurable: true
  51942. });
  51943. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  51944. get: function () {
  51945. return this.getRotationQuaternion();
  51946. },
  51947. set: function (newRotation) {
  51948. this.setRotationQuaternion(newRotation);
  51949. },
  51950. enumerable: true,
  51951. configurable: true
  51952. });
  51953. Object.defineProperty(Bone.prototype, "scaling", {
  51954. get: function () {
  51955. return this.getScale();
  51956. },
  51957. set: function (newScaling) {
  51958. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  51959. },
  51960. enumerable: true,
  51961. configurable: true
  51962. });
  51963. // Methods
  51964. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  51965. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  51966. this._baseMatrix = matrix.clone();
  51967. this._localMatrix = matrix.clone();
  51968. this._skeleton._markAsDirty();
  51969. if (updateDifferenceMatrix) {
  51970. this._updateDifferenceMatrix();
  51971. }
  51972. };
  51973. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  51974. if (!rootMatrix) {
  51975. rootMatrix = this._baseMatrix;
  51976. }
  51977. if (this._parent) {
  51978. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  51979. }
  51980. else {
  51981. this._absoluteTransform.copyFrom(rootMatrix);
  51982. }
  51983. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  51984. for (var index = 0; index < this.children.length; index++) {
  51985. this.children[index]._updateDifferenceMatrix();
  51986. }
  51987. };
  51988. Bone.prototype.markAsDirty = function () {
  51989. this._currentRenderId++;
  51990. this._skeleton._markAsDirty();
  51991. };
  51992. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  51993. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  51994. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  51995. // all animation may be coming from a library skeleton, so may need to create animation
  51996. if (this.animations.length === 0) {
  51997. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  51998. this.animations[0].setKeys([]);
  51999. }
  52000. // get animation info / verify there is such a range from the source bone
  52001. var sourceRange = source.animations[0].getRange(rangeName);
  52002. if (!sourceRange) {
  52003. return false;
  52004. }
  52005. var from = sourceRange.from;
  52006. var to = sourceRange.to;
  52007. var sourceKeys = source.animations[0].getKeys();
  52008. // rescaling prep
  52009. var sourceBoneLength = source.length;
  52010. var sourceParent = source.getParent();
  52011. var parent = this.getParent();
  52012. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  52013. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  52014. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  52015. var destKeys = this.animations[0].getKeys();
  52016. // loop vars declaration
  52017. var orig;
  52018. var origTranslation;
  52019. var mat;
  52020. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  52021. orig = sourceKeys[key];
  52022. if (orig.frame >= from && orig.frame <= to) {
  52023. if (rescaleAsRequired) {
  52024. mat = orig.value.clone();
  52025. // scale based on parent ratio, when bone has parent
  52026. if (parentScalingReqd) {
  52027. origTranslation = mat.getTranslation();
  52028. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  52029. // scale based on skeleton dimension ratio when root bone, and value is passed
  52030. }
  52031. else if (dimensionsScalingReqd) {
  52032. origTranslation = mat.getTranslation();
  52033. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  52034. // use original when root bone, and no data for skelDimensionsRatio
  52035. }
  52036. else {
  52037. mat = orig.value;
  52038. }
  52039. }
  52040. else {
  52041. mat = orig.value;
  52042. }
  52043. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  52044. }
  52045. }
  52046. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  52047. return true;
  52048. };
  52049. /**
  52050. * Translate the bone in local or world space.
  52051. * @param vec The amount to translate the bone.
  52052. * @param space The space that the translation is in.
  52053. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52054. */
  52055. Bone.prototype.translate = function (vec, space, mesh) {
  52056. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52057. var lm = this.getLocalMatrix();
  52058. if (space == BABYLON.Space.LOCAL) {
  52059. lm.m[12] += vec.x;
  52060. lm.m[13] += vec.y;
  52061. lm.m[14] += vec.z;
  52062. }
  52063. else {
  52064. var wm;
  52065. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52066. if (mesh) {
  52067. wm = mesh.getWorldMatrix();
  52068. }
  52069. this._skeleton.computeAbsoluteTransforms();
  52070. var tmat = Bone._tmpMats[0];
  52071. var tvec = Bone._tmpVecs[0];
  52072. if (mesh) {
  52073. tmat.copyFrom(this._parent.getAbsoluteTransform());
  52074. tmat.multiplyToRef(wm, tmat);
  52075. }
  52076. else {
  52077. tmat.copyFrom(this._parent.getAbsoluteTransform());
  52078. }
  52079. tmat.m[12] = 0;
  52080. tmat.m[13] = 0;
  52081. tmat.m[14] = 0;
  52082. tmat.invert();
  52083. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  52084. lm.m[12] += tvec.x;
  52085. lm.m[13] += tvec.y;
  52086. lm.m[14] += tvec.z;
  52087. }
  52088. this.markAsDirty();
  52089. };
  52090. /**
  52091. * Set the postion of the bone in local or world space.
  52092. * @param position The position to set the bone.
  52093. * @param space The space that the position is in.
  52094. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52095. */
  52096. Bone.prototype.setPosition = function (position, space, mesh) {
  52097. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52098. var lm = this.getLocalMatrix();
  52099. if (space == BABYLON.Space.LOCAL) {
  52100. lm.m[12] = position.x;
  52101. lm.m[13] = position.y;
  52102. lm.m[14] = position.z;
  52103. }
  52104. else {
  52105. var wm;
  52106. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52107. if (mesh) {
  52108. wm = mesh.getWorldMatrix();
  52109. }
  52110. this._skeleton.computeAbsoluteTransforms();
  52111. var tmat = Bone._tmpMats[0];
  52112. var vec = Bone._tmpVecs[0];
  52113. if (mesh) {
  52114. tmat.copyFrom(this._parent.getAbsoluteTransform());
  52115. tmat.multiplyToRef(wm, tmat);
  52116. }
  52117. else {
  52118. tmat.copyFrom(this._parent.getAbsoluteTransform());
  52119. }
  52120. tmat.invert();
  52121. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  52122. lm.m[12] = vec.x;
  52123. lm.m[13] = vec.y;
  52124. lm.m[14] = vec.z;
  52125. }
  52126. this.markAsDirty();
  52127. };
  52128. /**
  52129. * Set the absolute postion of the bone (world space).
  52130. * @param position The position to set the bone.
  52131. * @param mesh The mesh that this bone is attached to.
  52132. */
  52133. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  52134. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  52135. };
  52136. /**
  52137. * Set the scale of the bone on the x, y and z axes.
  52138. * @param x The scale of the bone on the x axis.
  52139. * @param x The scale of the bone on the y axis.
  52140. * @param z The scale of the bone on the z axis.
  52141. * @param scaleChildren Set this to true if children of the bone should be scaled.
  52142. */
  52143. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  52144. if (scaleChildren === void 0) { scaleChildren = false; }
  52145. if (this.animations[0] && !this.animations[0].isStopped()) {
  52146. if (!scaleChildren) {
  52147. this._negateScaleChildren.x = 1 / x;
  52148. this._negateScaleChildren.y = 1 / y;
  52149. this._negateScaleChildren.z = 1 / z;
  52150. }
  52151. this._syncScaleVector();
  52152. }
  52153. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  52154. };
  52155. /**
  52156. * Scale the bone on the x, y and z axes.
  52157. * @param x The amount to scale the bone on the x axis.
  52158. * @param x The amount to scale the bone on the y axis.
  52159. * @param z The amount to scale the bone on the z axis.
  52160. * @param scaleChildren Set this to true if children of the bone should be scaled.
  52161. */
  52162. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  52163. if (scaleChildren === void 0) { scaleChildren = false; }
  52164. var locMat = this.getLocalMatrix();
  52165. var origLocMat = Bone._tmpMats[0];
  52166. origLocMat.copyFrom(locMat);
  52167. var origLocMatInv = Bone._tmpMats[1];
  52168. origLocMatInv.copyFrom(origLocMat);
  52169. origLocMatInv.invert();
  52170. var scaleMat = Bone._tmpMats[2];
  52171. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  52172. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  52173. this._scaleVector.x *= x;
  52174. this._scaleVector.y *= y;
  52175. this._scaleVector.z *= z;
  52176. locMat.multiplyToRef(origLocMatInv, locMat);
  52177. locMat.multiplyToRef(scaleMat, locMat);
  52178. locMat.multiplyToRef(origLocMat, locMat);
  52179. var parent = this.getParent();
  52180. if (parent) {
  52181. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  52182. }
  52183. else {
  52184. this.getAbsoluteTransform().copyFrom(locMat);
  52185. }
  52186. var len = this.children.length;
  52187. scaleMat.invert();
  52188. for (var i = 0; i < len; i++) {
  52189. var child = this.children[i];
  52190. var cm = child.getLocalMatrix();
  52191. cm.multiplyToRef(scaleMat, cm);
  52192. var lm = child.getLocalMatrix();
  52193. lm.m[12] *= x;
  52194. lm.m[13] *= y;
  52195. lm.m[14] *= z;
  52196. }
  52197. this.computeAbsoluteTransforms();
  52198. if (scaleChildren) {
  52199. for (var i = 0; i < len; i++) {
  52200. this.children[i].scale(x, y, z, scaleChildren);
  52201. }
  52202. }
  52203. this.markAsDirty();
  52204. };
  52205. /**
  52206. * Set the yaw, pitch, and roll of the bone in local or world space.
  52207. * @param yaw The rotation of the bone on the y axis.
  52208. * @param pitch The rotation of the bone on the x axis.
  52209. * @param roll The rotation of the bone on the z axis.
  52210. * @param space The space that the axes of rotation are in.
  52211. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52212. */
  52213. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  52214. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52215. var rotMat = Bone._tmpMats[0];
  52216. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  52217. var rotMatInv = Bone._tmpMats[1];
  52218. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  52219. rotMatInv.multiplyToRef(rotMat, rotMat);
  52220. this._rotateWithMatrix(rotMat, space, mesh);
  52221. };
  52222. /**
  52223. * Rotate the bone on an axis in local or world space.
  52224. * @param axis The axis to rotate the bone on.
  52225. * @param amount The amount to rotate the bone.
  52226. * @param space The space that the axis is in.
  52227. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52228. */
  52229. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  52230. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52231. var rmat = Bone._tmpMats[0];
  52232. rmat.m[12] = 0;
  52233. rmat.m[13] = 0;
  52234. rmat.m[14] = 0;
  52235. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  52236. this._rotateWithMatrix(rmat, space, mesh);
  52237. };
  52238. /**
  52239. * Set the rotation of the bone to a particular axis angle in local or world space.
  52240. * @param axis The axis to rotate the bone on.
  52241. * @param angle The angle that the bone should be rotated to.
  52242. * @param space The space that the axis is in.
  52243. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52244. */
  52245. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  52246. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52247. var rotMat = Bone._tmpMats[0];
  52248. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  52249. var rotMatInv = Bone._tmpMats[1];
  52250. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  52251. rotMatInv.multiplyToRef(rotMat, rotMat);
  52252. this._rotateWithMatrix(rotMat, space, mesh);
  52253. };
  52254. /**
  52255. * Set the euler rotation of the bone in local of world space.
  52256. * @param rotation The euler rotation that the bone should be set to.
  52257. * @param space The space that the rotation is in.
  52258. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52259. */
  52260. Bone.prototype.setRotation = function (rotation, space, mesh) {
  52261. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52262. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  52263. };
  52264. /**
  52265. * Set the quaternion rotation of the bone in local of world space.
  52266. * @param quat The quaternion rotation that the bone should be set to.
  52267. * @param space The space that the rotation is in.
  52268. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52269. */
  52270. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  52271. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52272. var rotMatInv = Bone._tmpMats[0];
  52273. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  52274. var rotMat = Bone._tmpMats[1];
  52275. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  52276. rotMatInv.multiplyToRef(rotMat, rotMat);
  52277. this._rotateWithMatrix(rotMat, space, mesh);
  52278. };
  52279. /**
  52280. * Set the rotation matrix of the bone in local of world space.
  52281. * @param rotMat The rotation matrix that the bone should be set to.
  52282. * @param space The space that the rotation is in.
  52283. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52284. */
  52285. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  52286. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52287. var rotMatInv = Bone._tmpMats[0];
  52288. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  52289. var rotMat2 = Bone._tmpMats[1];
  52290. rotMat2.copyFrom(rotMat);
  52291. rotMatInv.multiplyToRef(rotMat, rotMat2);
  52292. this._rotateWithMatrix(rotMat2, space, mesh);
  52293. };
  52294. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  52295. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52296. var lmat = this.getLocalMatrix();
  52297. var lx = lmat.m[12];
  52298. var ly = lmat.m[13];
  52299. var lz = lmat.m[14];
  52300. var parent = this.getParent();
  52301. var parentScale = Bone._tmpMats[3];
  52302. var parentScaleInv = Bone._tmpMats[4];
  52303. if (parent) {
  52304. if (space == BABYLON.Space.WORLD) {
  52305. if (mesh) {
  52306. parentScale.copyFrom(mesh.getWorldMatrix());
  52307. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  52308. }
  52309. else {
  52310. parentScale.copyFrom(parent.getAbsoluteTransform());
  52311. }
  52312. }
  52313. else {
  52314. parentScale = parent._scaleMatrix;
  52315. }
  52316. parentScaleInv.copyFrom(parentScale);
  52317. parentScaleInv.invert();
  52318. lmat.multiplyToRef(parentScale, lmat);
  52319. lmat.multiplyToRef(rmat, lmat);
  52320. lmat.multiplyToRef(parentScaleInv, lmat);
  52321. }
  52322. else {
  52323. if (space == BABYLON.Space.WORLD && mesh) {
  52324. parentScale.copyFrom(mesh.getWorldMatrix());
  52325. parentScaleInv.copyFrom(parentScale);
  52326. parentScaleInv.invert();
  52327. lmat.multiplyToRef(parentScale, lmat);
  52328. lmat.multiplyToRef(rmat, lmat);
  52329. lmat.multiplyToRef(parentScaleInv, lmat);
  52330. }
  52331. else {
  52332. lmat.multiplyToRef(rmat, lmat);
  52333. }
  52334. }
  52335. lmat.m[12] = lx;
  52336. lmat.m[13] = ly;
  52337. lmat.m[14] = lz;
  52338. this.computeAbsoluteTransforms();
  52339. this.markAsDirty();
  52340. };
  52341. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  52342. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52343. if (space == BABYLON.Space.WORLD) {
  52344. var scaleMatrix = Bone._tmpMats[2];
  52345. scaleMatrix.copyFrom(this._scaleMatrix);
  52346. rotMatInv.copyFrom(this.getAbsoluteTransform());
  52347. if (mesh) {
  52348. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  52349. var meshScale = Bone._tmpMats[3];
  52350. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  52351. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  52352. }
  52353. rotMatInv.invert();
  52354. scaleMatrix.m[0] *= this._scalingDeterminant;
  52355. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  52356. }
  52357. else {
  52358. rotMatInv.copyFrom(this.getLocalMatrix());
  52359. rotMatInv.invert();
  52360. var scaleMatrix = Bone._tmpMats[2];
  52361. scaleMatrix.copyFrom(this._scaleMatrix);
  52362. if (this._parent) {
  52363. var pscaleMatrix = Bone._tmpMats[3];
  52364. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  52365. pscaleMatrix.invert();
  52366. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  52367. }
  52368. else {
  52369. scaleMatrix.m[0] *= this._scalingDeterminant;
  52370. }
  52371. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  52372. }
  52373. };
  52374. /**
  52375. * Get the scale of the bone
  52376. * @returns the scale of the bone
  52377. */
  52378. Bone.prototype.getScale = function () {
  52379. return this._scaleVector.clone();
  52380. };
  52381. /**
  52382. * Copy the scale of the bone to a vector3.
  52383. * @param result The vector3 to copy the scale to
  52384. */
  52385. Bone.prototype.getScaleToRef = function (result) {
  52386. result.copyFrom(this._scaleVector);
  52387. };
  52388. /**
  52389. * Get the position of the bone in local or world space.
  52390. * @param space The space that the returned position is in.
  52391. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52392. * @returns The position of the bone
  52393. */
  52394. Bone.prototype.getPosition = function (space, mesh) {
  52395. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52396. var pos = BABYLON.Vector3.Zero();
  52397. this.getPositionToRef(space, mesh, pos);
  52398. return pos;
  52399. };
  52400. /**
  52401. * Copy the position of the bone to a vector3 in local or world space.
  52402. * @param space The space that the returned position is in.
  52403. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52404. * @param result The vector3 to copy the position to.
  52405. */
  52406. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  52407. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52408. if (space == BABYLON.Space.LOCAL) {
  52409. var lm = this.getLocalMatrix();
  52410. result.x = lm.m[12];
  52411. result.y = lm.m[13];
  52412. result.z = lm.m[14];
  52413. }
  52414. else {
  52415. var wm;
  52416. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52417. if (mesh) {
  52418. wm = mesh.getWorldMatrix();
  52419. }
  52420. this._skeleton.computeAbsoluteTransforms();
  52421. var tmat = Bone._tmpMats[0];
  52422. if (mesh) {
  52423. tmat.copyFrom(this.getAbsoluteTransform());
  52424. tmat.multiplyToRef(wm, tmat);
  52425. }
  52426. else {
  52427. tmat = this.getAbsoluteTransform();
  52428. }
  52429. result.x = tmat.m[12];
  52430. result.y = tmat.m[13];
  52431. result.z = tmat.m[14];
  52432. }
  52433. };
  52434. /**
  52435. * Get the absolute position of the bone (world space).
  52436. * @param mesh The mesh that this bone is attached to.
  52437. * @returns The absolute position of the bone
  52438. */
  52439. Bone.prototype.getAbsolutePosition = function (mesh) {
  52440. var pos = BABYLON.Vector3.Zero();
  52441. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  52442. return pos;
  52443. };
  52444. /**
  52445. * Copy the absolute position of the bone (world space) to the result param.
  52446. * @param mesh The mesh that this bone is attached to.
  52447. * @param result The vector3 to copy the absolute position to.
  52448. */
  52449. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  52450. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  52451. };
  52452. /**
  52453. * Compute the absolute transforms of this bone and its children.
  52454. */
  52455. Bone.prototype.computeAbsoluteTransforms = function () {
  52456. if (this._parent) {
  52457. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  52458. }
  52459. else {
  52460. this._absoluteTransform.copyFrom(this._localMatrix);
  52461. var poseMatrix = this._skeleton.getPoseMatrix();
  52462. if (poseMatrix) {
  52463. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  52464. }
  52465. }
  52466. var children = this.children;
  52467. var len = children.length;
  52468. for (var i = 0; i < len; i++) {
  52469. children[i].computeAbsoluteTransforms();
  52470. }
  52471. };
  52472. Bone.prototype._syncScaleVector = function () {
  52473. var lm = this.getLocalMatrix();
  52474. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  52475. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  52476. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  52477. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  52478. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  52479. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  52480. this._scaleVector.x = xs * Math.sqrt(xsq);
  52481. this._scaleVector.y = ys * Math.sqrt(ysq);
  52482. this._scaleVector.z = zs * Math.sqrt(zsq);
  52483. if (this._parent) {
  52484. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  52485. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  52486. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  52487. }
  52488. 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);
  52489. };
  52490. /**
  52491. * Get the world direction from an axis that is in the local space of the bone.
  52492. * @param localAxis The local direction that is used to compute the world direction.
  52493. * @param mesh The mesh that this bone is attached to.
  52494. * @returns The world direction
  52495. */
  52496. Bone.prototype.getDirection = function (localAxis, mesh) {
  52497. var result = BABYLON.Vector3.Zero();
  52498. this.getDirectionToRef(localAxis, mesh, result);
  52499. return result;
  52500. };
  52501. /**
  52502. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  52503. * @param localAxis The local direction that is used to compute the world direction.
  52504. * @param mesh The mesh that this bone is attached to.
  52505. * @param result The vector3 that the world direction will be copied to.
  52506. */
  52507. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  52508. var wm;
  52509. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52510. if (mesh) {
  52511. wm = mesh.getWorldMatrix();
  52512. }
  52513. this._skeleton.computeAbsoluteTransforms();
  52514. var mat = Bone._tmpMats[0];
  52515. mat.copyFrom(this.getAbsoluteTransform());
  52516. if (mesh) {
  52517. mat.multiplyToRef(wm, mat);
  52518. }
  52519. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  52520. result.normalize();
  52521. };
  52522. /**
  52523. * Get the euler rotation of the bone in local or world space.
  52524. * @param space The space that the rotation should be in.
  52525. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52526. * @returns The euler rotation
  52527. */
  52528. Bone.prototype.getRotation = function (space, mesh) {
  52529. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52530. var result = BABYLON.Vector3.Zero();
  52531. this.getRotationToRef(space, mesh, result);
  52532. return result;
  52533. };
  52534. /**
  52535. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  52536. * @param space The space that the rotation should be in.
  52537. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52538. * @param result The vector3 that the rotation should be copied to.
  52539. */
  52540. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  52541. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52542. var quat = Bone._tmpQuat;
  52543. this.getRotationQuaternionToRef(space, mesh, quat);
  52544. quat.toEulerAnglesToRef(result);
  52545. };
  52546. /**
  52547. * Get the quaternion rotation of the bone in either local or world space.
  52548. * @param space The space that the rotation should be in.
  52549. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52550. * @returns The quaternion rotation
  52551. */
  52552. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  52553. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52554. var result = BABYLON.Quaternion.Identity();
  52555. this.getRotationQuaternionToRef(space, mesh, result);
  52556. return result;
  52557. };
  52558. /**
  52559. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  52560. * @param space The space that the rotation should be in.
  52561. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52562. * @param result The quaternion that the rotation should be copied to.
  52563. */
  52564. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  52565. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52566. if (space == BABYLON.Space.LOCAL) {
  52567. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  52568. }
  52569. else {
  52570. var mat = Bone._tmpMats[0];
  52571. var amat = this.getAbsoluteTransform();
  52572. if (mesh) {
  52573. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  52574. }
  52575. else {
  52576. mat.copyFrom(amat);
  52577. }
  52578. mat.m[0] *= this._scalingDeterminant;
  52579. mat.m[1] *= this._scalingDeterminant;
  52580. mat.m[2] *= this._scalingDeterminant;
  52581. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  52582. }
  52583. };
  52584. /**
  52585. * Get the rotation matrix of the bone in local or world space.
  52586. * @param space The space that the rotation should be in.
  52587. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52588. * @returns The rotation matrix
  52589. */
  52590. Bone.prototype.getRotationMatrix = function (space, mesh) {
  52591. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52592. var result = BABYLON.Matrix.Identity();
  52593. this.getRotationMatrixToRef(space, mesh, result);
  52594. return result;
  52595. };
  52596. /**
  52597. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  52598. * @param space The space that the rotation should be in.
  52599. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52600. * @param result The quaternion that the rotation should be copied to.
  52601. */
  52602. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  52603. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52604. if (space == BABYLON.Space.LOCAL) {
  52605. this.getLocalMatrix().getRotationMatrixToRef(result);
  52606. }
  52607. else {
  52608. var mat = Bone._tmpMats[0];
  52609. var amat = this.getAbsoluteTransform();
  52610. if (mesh) {
  52611. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  52612. }
  52613. else {
  52614. mat.copyFrom(amat);
  52615. }
  52616. mat.m[0] *= this._scalingDeterminant;
  52617. mat.m[1] *= this._scalingDeterminant;
  52618. mat.m[2] *= this._scalingDeterminant;
  52619. mat.getRotationMatrixToRef(result);
  52620. }
  52621. };
  52622. /**
  52623. * Get the world position of a point that is in the local space of the bone.
  52624. * @param position The local position
  52625. * @param mesh The mesh that this bone is attached to.
  52626. * @returns The world position
  52627. */
  52628. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  52629. var result = BABYLON.Vector3.Zero();
  52630. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  52631. return result;
  52632. };
  52633. /**
  52634. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  52635. * @param position The local position
  52636. * @param mesh The mesh that this bone is attached to.
  52637. * @param result The vector3 that the world position should be copied to.
  52638. */
  52639. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  52640. var wm;
  52641. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52642. if (mesh) {
  52643. wm = mesh.getWorldMatrix();
  52644. }
  52645. this._skeleton.computeAbsoluteTransforms();
  52646. var tmat = Bone._tmpMats[0];
  52647. if (mesh) {
  52648. tmat.copyFrom(this.getAbsoluteTransform());
  52649. tmat.multiplyToRef(wm, tmat);
  52650. }
  52651. else {
  52652. tmat = this.getAbsoluteTransform();
  52653. }
  52654. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  52655. };
  52656. /**
  52657. * Get the local position of a point that is in world space.
  52658. * @param position The world position
  52659. * @param mesh The mesh that this bone is attached to.
  52660. * @returns The local position
  52661. */
  52662. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  52663. var result = BABYLON.Vector3.Zero();
  52664. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  52665. return result;
  52666. };
  52667. /**
  52668. * Get the local position of a point that is in world space and copy it to the result param.
  52669. * @param position The world position
  52670. * @param mesh The mesh that this bone is attached to.
  52671. * @param result The vector3 that the local position should be copied to.
  52672. */
  52673. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  52674. var wm;
  52675. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52676. if (mesh) {
  52677. wm = mesh.getWorldMatrix();
  52678. }
  52679. this._skeleton.computeAbsoluteTransforms();
  52680. var tmat = Bone._tmpMats[0];
  52681. tmat.copyFrom(this.getAbsoluteTransform());
  52682. if (mesh) {
  52683. tmat.multiplyToRef(wm, tmat);
  52684. }
  52685. tmat.invert();
  52686. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  52687. };
  52688. return Bone;
  52689. }(BABYLON.Node));
  52690. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52691. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  52692. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  52693. BABYLON.Bone = Bone;
  52694. })(BABYLON || (BABYLON = {}));
  52695. //# sourceMappingURL=babylon.bone.js.map
  52696. var BABYLON;
  52697. (function (BABYLON) {
  52698. var BoneIKController = (function () {
  52699. function BoneIKController(mesh, bone, options) {
  52700. this.targetPosition = BABYLON.Vector3.Zero();
  52701. this.poleTargetPosition = BABYLON.Vector3.Zero();
  52702. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  52703. this.poleAngle = 0;
  52704. this.slerpAmount = 1;
  52705. this._bone1Quat = BABYLON.Quaternion.Identity();
  52706. this._bone1Mat = BABYLON.Matrix.Identity();
  52707. this._bone2Ang = Math.PI;
  52708. this._maxAngle = Math.PI;
  52709. this._rightHandedSystem = false;
  52710. this._bendAxis = BABYLON.Vector3.Right();
  52711. this._slerping = false;
  52712. this._adjustRoll = 0;
  52713. this._bone2 = bone;
  52714. this._bone1 = bone.getParent();
  52715. this.mesh = mesh;
  52716. var bonePos = bone.getPosition();
  52717. if (bone.getAbsoluteTransform().determinant() > 0) {
  52718. this._rightHandedSystem = true;
  52719. this._bendAxis.x = 0;
  52720. this._bendAxis.y = 0;
  52721. this._bendAxis.z = -1;
  52722. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  52723. this._adjustRoll = Math.PI * .5;
  52724. this._bendAxis.z = 1;
  52725. }
  52726. }
  52727. if (this._bone1.length) {
  52728. var boneScale1 = this._bone1.getScale();
  52729. var boneScale2 = this._bone2.getScale();
  52730. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  52731. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  52732. }
  52733. else if (this._bone1.children[0]) {
  52734. mesh.computeWorldMatrix(true);
  52735. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  52736. var pos2 = this._bone2.getAbsolutePosition(mesh);
  52737. var pos3 = this._bone1.getAbsolutePosition(mesh);
  52738. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  52739. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  52740. }
  52741. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  52742. this.maxAngle = Math.PI;
  52743. if (options) {
  52744. if (options.targetMesh) {
  52745. this.targetMesh = options.targetMesh;
  52746. this.targetMesh.computeWorldMatrix(true);
  52747. }
  52748. if (options.poleTargetMesh) {
  52749. this.poleTargetMesh = options.poleTargetMesh;
  52750. this.poleTargetMesh.computeWorldMatrix(true);
  52751. }
  52752. else if (options.poleTargetBone) {
  52753. this.poleTargetBone = options.poleTargetBone;
  52754. }
  52755. else if (this._bone1.getParent()) {
  52756. this.poleTargetBone = this._bone1.getParent();
  52757. }
  52758. if (options.poleTargetLocalOffset) {
  52759. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  52760. }
  52761. if (options.poleAngle) {
  52762. this.poleAngle = options.poleAngle;
  52763. }
  52764. if (options.bendAxis) {
  52765. this._bendAxis.copyFrom(options.bendAxis);
  52766. }
  52767. if (options.maxAngle) {
  52768. this.maxAngle = options.maxAngle;
  52769. }
  52770. if (options.slerpAmount) {
  52771. this.slerpAmount = options.slerpAmount;
  52772. }
  52773. }
  52774. }
  52775. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  52776. get: function () {
  52777. return this._maxAngle;
  52778. },
  52779. set: function (value) {
  52780. this._setMaxAngle(value);
  52781. },
  52782. enumerable: true,
  52783. configurable: true
  52784. });
  52785. BoneIKController.prototype._setMaxAngle = function (ang) {
  52786. if (ang < 0) {
  52787. ang = 0;
  52788. }
  52789. if (ang > Math.PI || ang == undefined) {
  52790. ang = Math.PI;
  52791. }
  52792. this._maxAngle = ang;
  52793. var a = this._bone1Length;
  52794. var b = this._bone2Length;
  52795. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  52796. };
  52797. BoneIKController.prototype.update = function () {
  52798. var bone1 = this._bone1;
  52799. var target = this.targetPosition;
  52800. var poleTarget = this.poleTargetPosition;
  52801. var mat1 = BoneIKController._tmpMats[0];
  52802. var mat2 = BoneIKController._tmpMats[1];
  52803. if (this.targetMesh) {
  52804. target.copyFrom(this.targetMesh.getAbsolutePosition());
  52805. }
  52806. if (this.poleTargetBone) {
  52807. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  52808. }
  52809. else if (this.poleTargetMesh) {
  52810. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  52811. }
  52812. var bonePos = BoneIKController._tmpVecs[0];
  52813. var zaxis = BoneIKController._tmpVecs[1];
  52814. var xaxis = BoneIKController._tmpVecs[2];
  52815. var yaxis = BoneIKController._tmpVecs[3];
  52816. var upAxis = BoneIKController._tmpVecs[4];
  52817. var _tmpQuat = BoneIKController._tmpQuat;
  52818. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  52819. poleTarget.subtractToRef(bonePos, upAxis);
  52820. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  52821. upAxis.y = 1;
  52822. }
  52823. else {
  52824. upAxis.normalize();
  52825. }
  52826. target.subtractToRef(bonePos, yaxis);
  52827. yaxis.normalize();
  52828. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  52829. zaxis.normalize();
  52830. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  52831. xaxis.normalize();
  52832. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  52833. var a = this._bone1Length;
  52834. var b = this._bone2Length;
  52835. var c = BABYLON.Vector3.Distance(bonePos, target);
  52836. if (this._maxReach > 0) {
  52837. c = Math.min(this._maxReach, c);
  52838. }
  52839. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  52840. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  52841. if (acosa > 1) {
  52842. acosa = 1;
  52843. }
  52844. if (acosb > 1) {
  52845. acosb = 1;
  52846. }
  52847. if (acosa < -1) {
  52848. acosa = -1;
  52849. }
  52850. if (acosb < -1) {
  52851. acosb = -1;
  52852. }
  52853. var angA = Math.acos(acosa);
  52854. var angB = Math.acos(acosb);
  52855. var angC = -angA - angB;
  52856. if (this._rightHandedSystem) {
  52857. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  52858. mat2.multiplyToRef(mat1, mat1);
  52859. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  52860. mat2.multiplyToRef(mat1, mat1);
  52861. }
  52862. else {
  52863. var _tmpVec = BoneIKController._tmpVecs[5];
  52864. _tmpVec.copyFrom(this._bendAxis);
  52865. _tmpVec.x *= -1;
  52866. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  52867. mat2.multiplyToRef(mat1, mat1);
  52868. }
  52869. if (this.poleAngle) {
  52870. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  52871. mat1.multiplyToRef(mat2, mat1);
  52872. }
  52873. if (this.slerpAmount < 1) {
  52874. if (!this._slerping) {
  52875. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  52876. }
  52877. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  52878. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  52879. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  52880. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  52881. this._slerping = true;
  52882. }
  52883. else {
  52884. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  52885. this._bone1Mat.copyFrom(mat1);
  52886. this._slerping = false;
  52887. }
  52888. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  52889. this._bone2Ang = angC;
  52890. };
  52891. return BoneIKController;
  52892. }());
  52893. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52894. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  52895. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  52896. BABYLON.BoneIKController = BoneIKController;
  52897. })(BABYLON || (BABYLON = {}));
  52898. //# sourceMappingURL=babylon.boneIKController.js.map
  52899. var BABYLON;
  52900. (function (BABYLON) {
  52901. var BoneLookController = (function () {
  52902. /**
  52903. * Create a BoneLookController
  52904. * @param mesh the mesh that the bone belongs to
  52905. * @param bone the bone that will be looking to the target
  52906. * @param target the target Vector3 to look at
  52907. * @param settings optional settings:
  52908. * - maxYaw: the maximum angle the bone will yaw to
  52909. * - minYaw: the minimum angle the bone will yaw to
  52910. * - maxPitch: the maximum angle the bone will pitch to
  52911. * - minPitch: the minimum angle the bone will yaw to
  52912. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  52913. * - upAxis: the up axis of the coordinate system
  52914. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  52915. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  52916. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  52917. * - adjustYaw: used to make an adjustment to the yaw of the bone
  52918. * - adjustPitch: used to make an adjustment to the pitch of the bone
  52919. * - adjustRoll: used to make an adjustment to the roll of the bone
  52920. **/
  52921. function BoneLookController(mesh, bone, target, options) {
  52922. /**
  52923. * The up axis of the coordinate system that is used when the bone is rotated.
  52924. */
  52925. this.upAxis = BABYLON.Vector3.Up();
  52926. /**
  52927. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  52928. */
  52929. this.upAxisSpace = BABYLON.Space.LOCAL;
  52930. /**
  52931. * Used to make an adjustment to the yaw of the bone.
  52932. */
  52933. this.adjustYaw = 0;
  52934. /**
  52935. * Used to make an adjustment to the pitch of the bone.
  52936. */
  52937. this.adjustPitch = 0;
  52938. /**
  52939. * Used to make an adjustment to the roll of the bone.
  52940. */
  52941. this.adjustRoll = 0;
  52942. /**
  52943. * 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).
  52944. */
  52945. this.slerpAmount = 1;
  52946. this._boneQuat = BABYLON.Quaternion.Identity();
  52947. this._slerping = false;
  52948. this._firstFrameSkipped = false;
  52949. this._fowardAxis = BABYLON.Vector3.Forward();
  52950. this.mesh = mesh;
  52951. this.bone = bone;
  52952. this.target = target;
  52953. if (options) {
  52954. if (options.adjustYaw) {
  52955. this.adjustYaw = options.adjustYaw;
  52956. }
  52957. if (options.adjustPitch) {
  52958. this.adjustPitch = options.adjustPitch;
  52959. }
  52960. if (options.adjustRoll) {
  52961. this.adjustRoll = options.adjustRoll;
  52962. }
  52963. if (options.maxYaw != null) {
  52964. this.maxYaw = options.maxYaw;
  52965. }
  52966. else {
  52967. this.maxYaw = Math.PI;
  52968. }
  52969. if (options.minYaw != null) {
  52970. this.minYaw = options.minYaw;
  52971. }
  52972. else {
  52973. this.minYaw = -Math.PI;
  52974. }
  52975. if (options.maxPitch != null) {
  52976. this.maxPitch = options.maxPitch;
  52977. }
  52978. else {
  52979. this.maxPitch = Math.PI;
  52980. }
  52981. if (options.minPitch != null) {
  52982. this.minPitch = options.minPitch;
  52983. }
  52984. else {
  52985. this.minPitch = -Math.PI;
  52986. }
  52987. if (options.slerpAmount != null) {
  52988. this.slerpAmount = options.slerpAmount;
  52989. }
  52990. if (options.upAxis != null) {
  52991. this.upAxis = options.upAxis;
  52992. }
  52993. if (options.upAxisSpace != null) {
  52994. this.upAxisSpace = options.upAxisSpace;
  52995. }
  52996. if (options.yawAxis != null || options.pitchAxis != null) {
  52997. var newYawAxis = BABYLON.Axis.Y;
  52998. var newPitchAxis = BABYLON.Axis.X;
  52999. if (options.yawAxis != null) {
  53000. newYawAxis = options.yawAxis.clone();
  53001. newYawAxis.normalize();
  53002. }
  53003. if (options.pitchAxis != null) {
  53004. newPitchAxis = options.pitchAxis.clone();
  53005. newPitchAxis.normalize();
  53006. }
  53007. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  53008. this._transformYawPitch = BABYLON.Matrix.Identity();
  53009. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  53010. this._transformYawPitchInv = this._transformYawPitch.clone();
  53011. this._transformYawPitch.invert();
  53012. }
  53013. }
  53014. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  53015. this.upAxisSpace = BABYLON.Space.LOCAL;
  53016. }
  53017. }
  53018. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  53019. /**
  53020. * Get/set the minimum yaw angle that the bone can look to.
  53021. */
  53022. get: function () {
  53023. return this._minYaw;
  53024. },
  53025. set: function (value) {
  53026. this._minYaw = value;
  53027. this._minYawSin = Math.sin(value);
  53028. this._minYawCos = Math.cos(value);
  53029. if (this._maxYaw != null) {
  53030. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  53031. this._yawRange = this._maxYaw - this._minYaw;
  53032. }
  53033. },
  53034. enumerable: true,
  53035. configurable: true
  53036. });
  53037. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  53038. /**
  53039. * Get/set the maximum yaw angle that the bone can look to.
  53040. */
  53041. get: function () {
  53042. return this._maxYaw;
  53043. },
  53044. set: function (value) {
  53045. this._maxYaw = value;
  53046. this._maxYawSin = Math.sin(value);
  53047. this._maxYawCos = Math.cos(value);
  53048. if (this._minYaw != null) {
  53049. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  53050. this._yawRange = this._maxYaw - this._minYaw;
  53051. }
  53052. },
  53053. enumerable: true,
  53054. configurable: true
  53055. });
  53056. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  53057. /**
  53058. * Get/set the minimum pitch angle that the bone can look to.
  53059. */
  53060. get: function () {
  53061. return this._minPitch;
  53062. },
  53063. set: function (value) {
  53064. this._minPitch = value;
  53065. this._minPitchTan = Math.tan(value);
  53066. },
  53067. enumerable: true,
  53068. configurable: true
  53069. });
  53070. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  53071. /**
  53072. * Get/set the maximum pitch angle that the bone can look to.
  53073. */
  53074. get: function () {
  53075. return this._maxPitch;
  53076. },
  53077. set: function (value) {
  53078. this._maxPitch = value;
  53079. this._maxPitchTan = Math.tan(value);
  53080. },
  53081. enumerable: true,
  53082. configurable: true
  53083. });
  53084. /**
  53085. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  53086. */
  53087. BoneLookController.prototype.update = function () {
  53088. //skip the first frame when slerping so that the mesh rotation is correct
  53089. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  53090. this._firstFrameSkipped = true;
  53091. return;
  53092. }
  53093. var bone = this.bone;
  53094. var bonePos = BoneLookController._tmpVecs[0];
  53095. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  53096. var target = this.target;
  53097. var _tmpMat1 = BoneLookController._tmpMats[0];
  53098. var _tmpMat2 = BoneLookController._tmpMats[1];
  53099. var mesh = this.mesh;
  53100. var parentBone = bone.getParent();
  53101. var upAxis = BoneLookController._tmpVecs[1];
  53102. upAxis.copyFrom(this.upAxis);
  53103. if (this.upAxisSpace == BABYLON.Space.BONE) {
  53104. if (this._transformYawPitch) {
  53105. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  53106. }
  53107. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  53108. }
  53109. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  53110. mesh.getDirectionToRef(upAxis, upAxis);
  53111. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  53112. upAxis.normalize();
  53113. }
  53114. }
  53115. var checkYaw = false;
  53116. var checkPitch = false;
  53117. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  53118. checkYaw = true;
  53119. }
  53120. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  53121. checkPitch = true;
  53122. }
  53123. if (checkYaw || checkPitch) {
  53124. var spaceMat = BoneLookController._tmpMats[2];
  53125. var spaceMatInv = BoneLookController._tmpMats[3];
  53126. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  53127. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  53128. }
  53129. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  53130. spaceMat.copyFrom(mesh.getWorldMatrix());
  53131. }
  53132. else {
  53133. var forwardAxis = BoneLookController._tmpVecs[2];
  53134. forwardAxis.copyFrom(this._fowardAxis);
  53135. if (this._transformYawPitch) {
  53136. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  53137. }
  53138. if (parentBone) {
  53139. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  53140. }
  53141. else {
  53142. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  53143. }
  53144. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  53145. rightAxis.normalize();
  53146. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  53147. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  53148. }
  53149. spaceMat.invertToRef(spaceMatInv);
  53150. var xzlen;
  53151. if (checkPitch) {
  53152. var localTarget = BoneLookController._tmpVecs[3];
  53153. target.subtractToRef(bonePos, localTarget);
  53154. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  53155. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  53156. var pitch = Math.atan2(localTarget.y, xzlen);
  53157. var newPitch = pitch;
  53158. if (pitch > this._maxPitch) {
  53159. localTarget.y = this._maxPitchTan * xzlen;
  53160. newPitch = this._maxPitch;
  53161. }
  53162. else if (pitch < this._minPitch) {
  53163. localTarget.y = this._minPitchTan * xzlen;
  53164. newPitch = this._minPitch;
  53165. }
  53166. if (pitch != newPitch) {
  53167. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  53168. localTarget.addInPlace(bonePos);
  53169. target = localTarget;
  53170. }
  53171. }
  53172. if (checkYaw) {
  53173. var localTarget = BoneLookController._tmpVecs[4];
  53174. target.subtractToRef(bonePos, localTarget);
  53175. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  53176. var yaw = Math.atan2(localTarget.x, localTarget.z);
  53177. var newYaw = yaw;
  53178. if (yaw > this._maxYaw || yaw < this._minYaw) {
  53179. if (xzlen == null) {
  53180. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  53181. }
  53182. if (this._yawRange > Math.PI) {
  53183. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  53184. localTarget.z = this._maxYawCos * xzlen;
  53185. localTarget.x = this._maxYawSin * xzlen;
  53186. newYaw = this._maxYaw;
  53187. }
  53188. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  53189. localTarget.z = this._minYawCos * xzlen;
  53190. localTarget.x = this._minYawSin * xzlen;
  53191. newYaw = this._minYaw;
  53192. }
  53193. }
  53194. else {
  53195. if (yaw > this._maxYaw) {
  53196. localTarget.z = this._maxYawCos * xzlen;
  53197. localTarget.x = this._maxYawSin * xzlen;
  53198. newYaw = this._maxYaw;
  53199. }
  53200. else if (yaw < this._minYaw) {
  53201. localTarget.z = this._minYawCos * xzlen;
  53202. localTarget.x = this._minYawSin * xzlen;
  53203. newYaw = this._minYaw;
  53204. }
  53205. }
  53206. }
  53207. if (this._slerping && this._yawRange > Math.PI) {
  53208. //are we going to be crossing into the min/max region?
  53209. var boneFwd = BoneLookController._tmpVecs[8];
  53210. boneFwd.copyFrom(BABYLON.Axis.Z);
  53211. if (this._transformYawPitch) {
  53212. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  53213. }
  53214. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  53215. this._boneQuat.toRotationMatrix(boneRotMat);
  53216. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  53217. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  53218. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  53219. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  53220. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  53221. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  53222. if (angBtwTar > angBtwMidYaw) {
  53223. if (xzlen == null) {
  53224. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  53225. }
  53226. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  53227. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  53228. if (angBtwMin < angBtwMax) {
  53229. newYaw = boneYaw + Math.PI * .75;
  53230. localTarget.z = Math.cos(newYaw) * xzlen;
  53231. localTarget.x = Math.sin(newYaw) * xzlen;
  53232. }
  53233. else {
  53234. newYaw = boneYaw - Math.PI * .75;
  53235. localTarget.z = Math.cos(newYaw) * xzlen;
  53236. localTarget.x = Math.sin(newYaw) * xzlen;
  53237. }
  53238. }
  53239. }
  53240. if (yaw != newYaw) {
  53241. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  53242. localTarget.addInPlace(bonePos);
  53243. target = localTarget;
  53244. }
  53245. }
  53246. }
  53247. var zaxis = BoneLookController._tmpVecs[5];
  53248. var xaxis = BoneLookController._tmpVecs[6];
  53249. var yaxis = BoneLookController._tmpVecs[7];
  53250. var _tmpQuat = BoneLookController._tmpQuat;
  53251. target.subtractToRef(bonePos, zaxis);
  53252. zaxis.normalize();
  53253. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  53254. xaxis.normalize();
  53255. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  53256. yaxis.normalize();
  53257. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  53258. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  53259. return;
  53260. }
  53261. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  53262. return;
  53263. }
  53264. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  53265. return;
  53266. }
  53267. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  53268. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  53269. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  53270. }
  53271. if (this.slerpAmount < 1) {
  53272. if (!this._slerping) {
  53273. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  53274. }
  53275. if (this._transformYawPitch) {
  53276. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  53277. }
  53278. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  53279. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  53280. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  53281. this._slerping = true;
  53282. }
  53283. else {
  53284. if (this._transformYawPitch) {
  53285. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  53286. }
  53287. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  53288. this._slerping = false;
  53289. }
  53290. };
  53291. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  53292. var angDiff = ang2 - ang1;
  53293. angDiff %= Math.PI * 2;
  53294. if (angDiff > Math.PI) {
  53295. angDiff -= Math.PI * 2;
  53296. }
  53297. else if (angDiff < -Math.PI) {
  53298. angDiff += Math.PI * 2;
  53299. }
  53300. return angDiff;
  53301. };
  53302. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  53303. ang1 %= (2 * Math.PI);
  53304. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  53305. ang2 %= (2 * Math.PI);
  53306. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  53307. var ab = 0;
  53308. if (ang1 < ang2) {
  53309. ab = ang2 - ang1;
  53310. }
  53311. else {
  53312. ab = ang1 - ang2;
  53313. }
  53314. if (ab > Math.PI) {
  53315. ab = Math.PI * 2 - ab;
  53316. }
  53317. return ab;
  53318. };
  53319. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  53320. ang %= (2 * Math.PI);
  53321. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  53322. ang1 %= (2 * Math.PI);
  53323. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  53324. ang2 %= (2 * Math.PI);
  53325. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  53326. if (ang1 < ang2) {
  53327. if (ang > ang1 && ang < ang2) {
  53328. return true;
  53329. }
  53330. }
  53331. else {
  53332. if (ang > ang2 && ang < ang1) {
  53333. return true;
  53334. }
  53335. }
  53336. return false;
  53337. };
  53338. return BoneLookController;
  53339. }());
  53340. 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()];
  53341. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  53342. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  53343. BABYLON.BoneLookController = BoneLookController;
  53344. })(BABYLON || (BABYLON = {}));
  53345. //# sourceMappingURL=babylon.boneLookController.js.map
  53346. var BABYLON;
  53347. (function (BABYLON) {
  53348. var Skeleton = (function () {
  53349. function Skeleton(name, id, scene) {
  53350. this.name = name;
  53351. this.id = id;
  53352. this.bones = new Array();
  53353. this.needInitialSkinMatrix = false;
  53354. this._isDirty = true;
  53355. this._meshesWithPoseMatrix = new Array();
  53356. this._identity = BABYLON.Matrix.Identity();
  53357. this._ranges = {};
  53358. this._lastAbsoluteTransformsUpdateId = -1;
  53359. // Events
  53360. /**
  53361. * An event triggered before computing the skeleton's matrices
  53362. * @type {BABYLON.Observable}
  53363. */
  53364. this.onBeforeComputeObservable = new BABYLON.Observable();
  53365. this.bones = [];
  53366. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53367. scene.skeletons.push(this);
  53368. //make sure it will recalculate the matrix next time prepare is called.
  53369. this._isDirty = true;
  53370. }
  53371. // Members
  53372. Skeleton.prototype.getTransformMatrices = function (mesh) {
  53373. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  53374. return mesh._bonesTransformMatrices;
  53375. }
  53376. if (!this._transformMatrices) {
  53377. this.prepare();
  53378. }
  53379. return this._transformMatrices;
  53380. };
  53381. Skeleton.prototype.getScene = function () {
  53382. return this._scene;
  53383. };
  53384. // Methods
  53385. /**
  53386. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  53387. */
  53388. Skeleton.prototype.toString = function (fullDetails) {
  53389. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  53390. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  53391. if (fullDetails) {
  53392. ret += ", Ranges: {";
  53393. var first = true;
  53394. for (var name_1 in this._ranges) {
  53395. if (first) {
  53396. ret += ", ";
  53397. first = false;
  53398. }
  53399. ret += name_1;
  53400. }
  53401. ret += "}";
  53402. }
  53403. return ret;
  53404. };
  53405. /**
  53406. * Get bone's index searching by name
  53407. * @param {string} name is bone's name to search for
  53408. * @return {number} Indice of the bone. Returns -1 if not found
  53409. */
  53410. Skeleton.prototype.getBoneIndexByName = function (name) {
  53411. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  53412. if (this.bones[boneIndex].name === name) {
  53413. return boneIndex;
  53414. }
  53415. }
  53416. return -1;
  53417. };
  53418. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  53419. // check name not already in use
  53420. if (!this._ranges[name]) {
  53421. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  53422. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  53423. if (this.bones[i].animations[0]) {
  53424. this.bones[i].animations[0].createRange(name, from, to);
  53425. }
  53426. }
  53427. }
  53428. };
  53429. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  53430. if (deleteFrames === void 0) { deleteFrames = true; }
  53431. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  53432. if (this.bones[i].animations[0]) {
  53433. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  53434. }
  53435. }
  53436. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  53437. };
  53438. Skeleton.prototype.getAnimationRange = function (name) {
  53439. return this._ranges[name];
  53440. };
  53441. /**
  53442. * Returns as an Array, all AnimationRanges defined on this skeleton
  53443. */
  53444. Skeleton.prototype.getAnimationRanges = function () {
  53445. var animationRanges = [];
  53446. var name;
  53447. var i = 0;
  53448. for (name in this._ranges) {
  53449. animationRanges[i] = this._ranges[name];
  53450. i++;
  53451. }
  53452. return animationRanges;
  53453. };
  53454. /**
  53455. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  53456. */
  53457. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  53458. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  53459. if (this._ranges[name] || !source.getAnimationRange(name)) {
  53460. return false;
  53461. }
  53462. var ret = true;
  53463. var frameOffset = this._getHighestAnimationFrame() + 1;
  53464. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  53465. var boneDict = {};
  53466. var sourceBones = source.bones;
  53467. var nBones;
  53468. var i;
  53469. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  53470. boneDict[sourceBones[i].name] = sourceBones[i];
  53471. }
  53472. if (this.bones.length !== sourceBones.length) {
  53473. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  53474. ret = false;
  53475. }
  53476. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  53477. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  53478. var boneName = this.bones[i].name;
  53479. var sourceBone = boneDict[boneName];
  53480. if (sourceBone) {
  53481. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  53482. }
  53483. else {
  53484. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  53485. ret = false;
  53486. }
  53487. }
  53488. // do not call createAnimationRange(), since it also is done to bones, which was already done
  53489. var range = source.getAnimationRange(name);
  53490. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  53491. return ret;
  53492. };
  53493. Skeleton.prototype.returnToRest = function () {
  53494. for (var index = 0; index < this.bones.length; index++) {
  53495. this.bones[index].returnToRest();
  53496. }
  53497. };
  53498. Skeleton.prototype._getHighestAnimationFrame = function () {
  53499. var ret = 0;
  53500. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  53501. if (this.bones[i].animations[0]) {
  53502. var highest = this.bones[i].animations[0].getHighestFrame();
  53503. if (ret < highest) {
  53504. ret = highest;
  53505. }
  53506. }
  53507. }
  53508. return ret;
  53509. };
  53510. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  53511. var range = this.getAnimationRange(name);
  53512. if (!range) {
  53513. return null;
  53514. }
  53515. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  53516. };
  53517. Skeleton.prototype._markAsDirty = function () {
  53518. this._isDirty = true;
  53519. };
  53520. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  53521. this._meshesWithPoseMatrix.push(mesh);
  53522. };
  53523. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  53524. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  53525. if (index > -1) {
  53526. this._meshesWithPoseMatrix.splice(index, 1);
  53527. }
  53528. };
  53529. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  53530. this.onBeforeComputeObservable.notifyObservers(this);
  53531. for (var index = 0; index < this.bones.length; index++) {
  53532. var bone = this.bones[index];
  53533. var parentBone = bone.getParent();
  53534. if (parentBone) {
  53535. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  53536. }
  53537. else {
  53538. if (initialSkinMatrix) {
  53539. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  53540. }
  53541. else {
  53542. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  53543. }
  53544. }
  53545. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  53546. }
  53547. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  53548. };
  53549. Skeleton.prototype.prepare = function () {
  53550. if (!this._isDirty) {
  53551. return;
  53552. }
  53553. if (this.needInitialSkinMatrix) {
  53554. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  53555. var mesh = this._meshesWithPoseMatrix[index];
  53556. var poseMatrix = mesh.getPoseMatrix();
  53557. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  53558. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  53559. }
  53560. if (this._synchronizedWithMesh !== mesh) {
  53561. this._synchronizedWithMesh = mesh;
  53562. // Prepare bones
  53563. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  53564. var bone = this.bones[boneIndex];
  53565. if (!bone.getParent()) {
  53566. var matrix = bone.getBaseMatrix();
  53567. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  53568. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  53569. }
  53570. }
  53571. }
  53572. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  53573. }
  53574. }
  53575. else {
  53576. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  53577. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  53578. }
  53579. this._computeTransformMatrices(this._transformMatrices, null);
  53580. }
  53581. this._isDirty = false;
  53582. this._scene._activeBones.addCount(this.bones.length, false);
  53583. };
  53584. Skeleton.prototype.getAnimatables = function () {
  53585. if (!this._animatables || this._animatables.length !== this.bones.length) {
  53586. this._animatables = [];
  53587. for (var index = 0; index < this.bones.length; index++) {
  53588. this._animatables.push(this.bones[index]);
  53589. }
  53590. }
  53591. return this._animatables;
  53592. };
  53593. Skeleton.prototype.clone = function (name, id) {
  53594. var result = new Skeleton(name, id || name, this._scene);
  53595. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  53596. for (var index = 0; index < this.bones.length; index++) {
  53597. var source = this.bones[index];
  53598. var parentBone = null;
  53599. if (source.getParent()) {
  53600. var parentIndex = this.bones.indexOf(source.getParent());
  53601. parentBone = result.bones[parentIndex];
  53602. }
  53603. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  53604. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  53605. }
  53606. if (this._ranges) {
  53607. result._ranges = {};
  53608. for (var rangeName in this._ranges) {
  53609. result._ranges[rangeName] = this._ranges[rangeName].clone();
  53610. }
  53611. }
  53612. this._isDirty = true;
  53613. return result;
  53614. };
  53615. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  53616. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  53617. this.bones.forEach(function (bone) {
  53618. bone.animations.forEach(function (animation) {
  53619. animation.enableBlending = true;
  53620. animation.blendingSpeed = blendingSpeed;
  53621. });
  53622. });
  53623. };
  53624. Skeleton.prototype.dispose = function () {
  53625. this._meshesWithPoseMatrix = [];
  53626. // Animations
  53627. this.getScene().stopAnimation(this);
  53628. // Remove from scene
  53629. this.getScene().removeSkeleton(this);
  53630. };
  53631. Skeleton.prototype.serialize = function () {
  53632. var serializationObject = {};
  53633. serializationObject.name = this.name;
  53634. serializationObject.id = this.id;
  53635. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  53636. serializationObject.bones = [];
  53637. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  53638. for (var index = 0; index < this.bones.length; index++) {
  53639. var bone = this.bones[index];
  53640. var serializedBone = {
  53641. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  53642. name: bone.name,
  53643. matrix: bone.getBaseMatrix().toArray(),
  53644. rest: bone.getRestPose().toArray()
  53645. };
  53646. serializationObject.bones.push(serializedBone);
  53647. if (bone.length) {
  53648. serializedBone.length = bone.length;
  53649. }
  53650. if (bone.animations && bone.animations.length > 0) {
  53651. serializedBone.animation = bone.animations[0].serialize();
  53652. }
  53653. serializationObject.ranges = [];
  53654. for (var name in this._ranges) {
  53655. var range = {};
  53656. range.name = name;
  53657. range.from = this._ranges[name].from;
  53658. range.to = this._ranges[name].to;
  53659. serializationObject.ranges.push(range);
  53660. }
  53661. }
  53662. return serializationObject;
  53663. };
  53664. Skeleton.Parse = function (parsedSkeleton, scene) {
  53665. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  53666. if (parsedSkeleton.dimensionsAtRest) {
  53667. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  53668. }
  53669. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  53670. var index;
  53671. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  53672. var parsedBone = parsedSkeleton.bones[index];
  53673. var parentBone = null;
  53674. if (parsedBone.parentBoneIndex > -1) {
  53675. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  53676. }
  53677. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  53678. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  53679. if (parsedBone.length) {
  53680. bone.length = parsedBone.length;
  53681. }
  53682. if (parsedBone.animation) {
  53683. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  53684. }
  53685. }
  53686. // placed after bones, so createAnimationRange can cascade down
  53687. if (parsedSkeleton.ranges) {
  53688. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  53689. var data = parsedSkeleton.ranges[index];
  53690. skeleton.createAnimationRange(data.name, data.from, data.to);
  53691. }
  53692. }
  53693. return skeleton;
  53694. };
  53695. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  53696. if (forceUpdate === void 0) { forceUpdate = false; }
  53697. var renderId = this._scene.getRenderId();
  53698. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  53699. this.bones[0].computeAbsoluteTransforms();
  53700. this._lastAbsoluteTransformsUpdateId = renderId;
  53701. }
  53702. };
  53703. Skeleton.prototype.getPoseMatrix = function () {
  53704. var poseMatrix;
  53705. if (this._meshesWithPoseMatrix.length > 0) {
  53706. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  53707. }
  53708. return poseMatrix;
  53709. };
  53710. return Skeleton;
  53711. }());
  53712. BABYLON.Skeleton = Skeleton;
  53713. })(BABYLON || (BABYLON = {}));
  53714. //# sourceMappingURL=babylon.skeleton.js.map
  53715. var BABYLON;
  53716. (function (BABYLON) {
  53717. var Internals;
  53718. (function (Internals) {
  53719. var FileFaceOrientation = (function () {
  53720. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  53721. this.name = name;
  53722. this.worldAxisForNormal = worldAxisForNormal;
  53723. this.worldAxisForFileX = worldAxisForFileX;
  53724. this.worldAxisForFileY = worldAxisForFileY;
  53725. }
  53726. return FileFaceOrientation;
  53727. }());
  53728. ;
  53729. /**
  53730. * Helper class dealing with the extraction of spherical polynomial dataArray
  53731. * from a cube map.
  53732. */
  53733. var CubeMapToSphericalPolynomialTools = (function () {
  53734. function CubeMapToSphericalPolynomialTools() {
  53735. }
  53736. /**
  53737. * Converts a cubemap to the according Spherical Polynomial data.
  53738. * This extracts the first 3 orders only as they are the only one used in the lighting.
  53739. *
  53740. * @param cubeInfo The Cube map to extract the information from.
  53741. * @return The Spherical Polynomial data.
  53742. */
  53743. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  53744. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  53745. var totalSolidAngle = 0.0;
  53746. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  53747. var du = 2.0 / cubeInfo.size;
  53748. var dv = du;
  53749. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  53750. var minUV = du * 0.5 - 1.0;
  53751. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  53752. var fileFace = this.FileFaces[faceIndex];
  53753. var dataArray = cubeInfo[fileFace.name];
  53754. var v = minUV;
  53755. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  53756. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  53757. // Because SP is still linear, so summation is fine in that basis.
  53758. for (var y = 0; y < cubeInfo.size; y++) {
  53759. var u = minUV;
  53760. for (var x = 0; x < cubeInfo.size; x++) {
  53761. // World direction (not normalised)
  53762. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  53763. worldDirection.normalize();
  53764. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  53765. if (1) {
  53766. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  53767. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  53768. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  53769. var color = new BABYLON.Color3(r, g, b);
  53770. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53771. }
  53772. else {
  53773. if (faceIndex == 0) {
  53774. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53775. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53776. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53777. }
  53778. else if (faceIndex == 1) {
  53779. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53780. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53781. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53782. }
  53783. else if (faceIndex == 2) {
  53784. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53785. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53786. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53787. }
  53788. else if (faceIndex == 3) {
  53789. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53790. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53791. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53792. }
  53793. else if (faceIndex == 4) {
  53794. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53795. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53796. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53797. }
  53798. else if (faceIndex == 5) {
  53799. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53800. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53801. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53802. }
  53803. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  53804. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53805. }
  53806. totalSolidAngle += deltaSolidAngle;
  53807. u += du;
  53808. }
  53809. v += dv;
  53810. }
  53811. }
  53812. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  53813. var correction = correctSolidAngle / totalSolidAngle;
  53814. sphericalHarmonics.scale(correction);
  53815. // Additionally scale by pi -- audit needed
  53816. sphericalHarmonics.scale(1.0 / Math.PI);
  53817. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  53818. };
  53819. return CubeMapToSphericalPolynomialTools;
  53820. }());
  53821. CubeMapToSphericalPolynomialTools.FileFaces = [
  53822. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  53823. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  53824. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  53825. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  53826. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  53827. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  53828. ];
  53829. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  53830. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53831. })(BABYLON || (BABYLON = {}));
  53832. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  53833. var BABYLON;
  53834. (function (BABYLON) {
  53835. var Internals;
  53836. (function (Internals) {
  53837. /**
  53838. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  53839. */
  53840. var PanoramaToCubeMapTools = (function () {
  53841. function PanoramaToCubeMapTools() {
  53842. }
  53843. /**
  53844. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  53845. *
  53846. * @param float32Array The source data.
  53847. * @param inputWidth The width of the input panorama.
  53848. * @param inputhHeight The height of the input panorama.
  53849. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  53850. * @return The cubemap data
  53851. */
  53852. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  53853. if (!float32Array) {
  53854. throw "ConvertPanoramaToCubemap: input cannot be null";
  53855. }
  53856. if (float32Array.length != inputWidth * inputHeight * 3) {
  53857. throw "ConvertPanoramaToCubemap: input size is wrong";
  53858. }
  53859. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  53860. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  53861. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  53862. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  53863. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  53864. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  53865. return {
  53866. front: textureFront,
  53867. back: textureBack,
  53868. left: textureLeft,
  53869. right: textureRight,
  53870. up: textureUp,
  53871. down: textureDown,
  53872. size: size
  53873. };
  53874. };
  53875. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  53876. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  53877. var textureArray = new Float32Array(buffer);
  53878. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  53879. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  53880. var dy = 1 / texSize;
  53881. var fy = 0;
  53882. for (var y = 0; y < texSize; y++) {
  53883. var xv1 = faceData[0];
  53884. var xv2 = faceData[2];
  53885. for (var x = 0; x < texSize; x++) {
  53886. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  53887. v.normalize();
  53888. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  53889. // 3 channels per pixels
  53890. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  53891. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  53892. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  53893. xv1 = xv1.add(rotDX1);
  53894. xv2 = xv2.add(rotDX2);
  53895. }
  53896. fy += dy;
  53897. }
  53898. return textureArray;
  53899. };
  53900. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  53901. var theta = Math.atan2(vDir.z, vDir.x);
  53902. var phi = Math.acos(vDir.y);
  53903. while (theta < -Math.PI)
  53904. theta += 2 * Math.PI;
  53905. while (theta > Math.PI)
  53906. theta -= 2 * Math.PI;
  53907. var dx = theta / Math.PI;
  53908. var dy = phi / Math.PI;
  53909. // recenter.
  53910. dx = dx * 0.5 + 0.5;
  53911. var px = Math.round(dx * inputWidth);
  53912. if (px < 0)
  53913. px = 0;
  53914. else if (px >= inputWidth)
  53915. px = inputWidth - 1;
  53916. var py = Math.round(dy * inputHeight);
  53917. if (py < 0)
  53918. py = 0;
  53919. else if (py >= inputHeight)
  53920. py = inputHeight - 1;
  53921. var inputY = (inputHeight - py - 1);
  53922. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  53923. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  53924. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  53925. return {
  53926. r: r,
  53927. g: g,
  53928. b: b
  53929. };
  53930. };
  53931. return PanoramaToCubeMapTools;
  53932. }());
  53933. PanoramaToCubeMapTools.FACE_FRONT = [
  53934. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53935. new BABYLON.Vector3(1.0, -1.0, -1.0),
  53936. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  53937. new BABYLON.Vector3(1.0, 1.0, -1.0)
  53938. ];
  53939. PanoramaToCubeMapTools.FACE_BACK = [
  53940. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53941. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53942. new BABYLON.Vector3(1.0, 1.0, 1.0),
  53943. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  53944. ];
  53945. PanoramaToCubeMapTools.FACE_RIGHT = [
  53946. new BABYLON.Vector3(1.0, -1.0, -1.0),
  53947. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53948. new BABYLON.Vector3(1.0, 1.0, -1.0),
  53949. new BABYLON.Vector3(1.0, 1.0, 1.0)
  53950. ];
  53951. PanoramaToCubeMapTools.FACE_LEFT = [
  53952. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53953. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53954. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  53955. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  53956. ];
  53957. PanoramaToCubeMapTools.FACE_DOWN = [
  53958. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  53959. new BABYLON.Vector3(1.0, 1.0, -1.0),
  53960. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  53961. new BABYLON.Vector3(1.0, 1.0, 1.0)
  53962. ];
  53963. PanoramaToCubeMapTools.FACE_UP = [
  53964. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53965. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53966. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53967. new BABYLON.Vector3(1.0, -1.0, -1.0)
  53968. ];
  53969. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  53970. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53971. })(BABYLON || (BABYLON = {}));
  53972. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  53973. var BABYLON;
  53974. (function (BABYLON) {
  53975. var Internals;
  53976. (function (Internals) {
  53977. ;
  53978. /**
  53979. * This groups tools to convert HDR texture to native colors array.
  53980. */
  53981. var HDRTools = (function () {
  53982. function HDRTools() {
  53983. }
  53984. HDRTools.Ldexp = function (mantissa, exponent) {
  53985. if (exponent > 1023) {
  53986. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  53987. }
  53988. if (exponent < -1074) {
  53989. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  53990. }
  53991. return mantissa * Math.pow(2, exponent);
  53992. };
  53993. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  53994. if (exponent > 0) {
  53995. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  53996. float32array[index + 0] = red * exponent;
  53997. float32array[index + 1] = green * exponent;
  53998. float32array[index + 2] = blue * exponent;
  53999. }
  54000. else {
  54001. float32array[index + 0] = 0;
  54002. float32array[index + 1] = 0;
  54003. float32array[index + 2] = 0;
  54004. }
  54005. };
  54006. HDRTools.readStringLine = function (uint8array, startIndex) {
  54007. var line = "";
  54008. var character = "";
  54009. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  54010. character = String.fromCharCode(uint8array[i]);
  54011. if (character == "\n") {
  54012. break;
  54013. }
  54014. line += character;
  54015. }
  54016. return line;
  54017. };
  54018. /**
  54019. * Reads header information from an RGBE texture stored in a native array.
  54020. * More information on this format are available here:
  54021. * https://en.wikipedia.org/wiki/RGBE_image_format
  54022. *
  54023. * @param uint8array The binary file stored in native array.
  54024. * @return The header information.
  54025. */
  54026. HDRTools.RGBE_ReadHeader = function (uint8array) {
  54027. var height = 0;
  54028. var width = 0;
  54029. var line = this.readStringLine(uint8array, 0);
  54030. if (line[0] != '#' || line[1] != '?') {
  54031. throw "Bad HDR Format.";
  54032. }
  54033. var endOfHeader = false;
  54034. var findFormat = false;
  54035. var lineIndex = 0;
  54036. do {
  54037. lineIndex += (line.length + 1);
  54038. line = this.readStringLine(uint8array, lineIndex);
  54039. if (line == "FORMAT=32-bit_rle_rgbe") {
  54040. findFormat = true;
  54041. }
  54042. else if (line.length == 0) {
  54043. endOfHeader = true;
  54044. }
  54045. } while (!endOfHeader);
  54046. if (!findFormat) {
  54047. throw "HDR Bad header format, unsupported FORMAT";
  54048. }
  54049. lineIndex += (line.length + 1);
  54050. line = this.readStringLine(uint8array, lineIndex);
  54051. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  54052. var match = sizeRegexp.exec(line);
  54053. // TODO. Support +Y and -X if needed.
  54054. if (match.length < 3) {
  54055. throw "HDR Bad header format, no size";
  54056. }
  54057. width = parseInt(match[2]);
  54058. height = parseInt(match[1]);
  54059. if (width < 8 || width > 0x7fff) {
  54060. throw "HDR Bad header format, unsupported size";
  54061. }
  54062. lineIndex += (line.length + 1);
  54063. return {
  54064. height: height,
  54065. width: width,
  54066. dataPosition: lineIndex
  54067. };
  54068. };
  54069. /**
  54070. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  54071. * This RGBE texture needs to store the information as a panorama.
  54072. *
  54073. * More information on this format are available here:
  54074. * https://en.wikipedia.org/wiki/RGBE_image_format
  54075. *
  54076. * @param buffer The binary file stored in an array buffer.
  54077. * @param size The expected size of the extracted cubemap.
  54078. * @return The Cube Map information.
  54079. */
  54080. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  54081. var uint8array = new Uint8Array(buffer);
  54082. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  54083. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  54084. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  54085. return cubeMapData;
  54086. };
  54087. /**
  54088. * Returns the pixels data extracted from an RGBE texture.
  54089. * This pixels will be stored left to right up to down in the R G B order in one array.
  54090. *
  54091. * More information on this format are available here:
  54092. * https://en.wikipedia.org/wiki/RGBE_image_format
  54093. *
  54094. * @param uint8array The binary file stored in an array buffer.
  54095. * @param hdrInfo The header information of the file.
  54096. * @return The pixels data in RGB right to left up to down order.
  54097. */
  54098. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  54099. // Keep for multi format supports.
  54100. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  54101. };
  54102. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  54103. var num_scanlines = hdrInfo.height;
  54104. var scanline_width = hdrInfo.width;
  54105. var a, b, c, d, count;
  54106. var dataIndex = hdrInfo.dataPosition;
  54107. var index = 0, endIndex = 0, i = 0;
  54108. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  54109. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  54110. // 3 channels of 4 bytes per pixel in float.
  54111. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  54112. var resultArray = new Float32Array(resultBuffer);
  54113. // read in each successive scanline
  54114. while (num_scanlines > 0) {
  54115. a = uint8array[dataIndex++];
  54116. b = uint8array[dataIndex++];
  54117. c = uint8array[dataIndex++];
  54118. d = uint8array[dataIndex++];
  54119. if (a != 2 || b != 2 || (c & 0x80)) {
  54120. // this file is not run length encoded
  54121. throw "HDR Bad header format, not RLE";
  54122. }
  54123. if (((c << 8) | d) != scanline_width) {
  54124. throw "HDR Bad header format, wrong scan line width";
  54125. }
  54126. index = 0;
  54127. // read each of the four channels for the scanline into the buffer
  54128. for (i = 0; i < 4; i++) {
  54129. endIndex = (i + 1) * scanline_width;
  54130. while (index < endIndex) {
  54131. a = uint8array[dataIndex++];
  54132. b = uint8array[dataIndex++];
  54133. if (a > 128) {
  54134. // a run of the same value
  54135. count = a - 128;
  54136. if ((count == 0) || (count > endIndex - index)) {
  54137. throw "HDR Bad Format, bad scanline data (run)";
  54138. }
  54139. while (count-- > 0) {
  54140. scanLineArray[index++] = b;
  54141. }
  54142. }
  54143. else {
  54144. // a non-run
  54145. count = a;
  54146. if ((count == 0) || (count > endIndex - index)) {
  54147. throw "HDR Bad Format, bad scanline data (non-run)";
  54148. }
  54149. scanLineArray[index++] = b;
  54150. if (--count > 0) {
  54151. for (var j = 0; j < count; j++) {
  54152. scanLineArray[index++] = uint8array[dataIndex++];
  54153. }
  54154. }
  54155. }
  54156. }
  54157. }
  54158. // now convert data from buffer into floats
  54159. for (i = 0; i < scanline_width; i++) {
  54160. a = scanLineArray[i];
  54161. b = scanLineArray[i + scanline_width];
  54162. c = scanLineArray[i + 2 * scanline_width];
  54163. d = scanLineArray[i + 3 * scanline_width];
  54164. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  54165. }
  54166. num_scanlines--;
  54167. }
  54168. return resultArray;
  54169. };
  54170. return HDRTools;
  54171. }());
  54172. Internals.HDRTools = HDRTools;
  54173. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54174. })(BABYLON || (BABYLON = {}));
  54175. //# sourceMappingURL=babylon.hdr.js.map
  54176. //_______________________________________________________________
  54177. // Extracted from CubeMapGen:
  54178. // https://code.google.com/archive/p/cubemapgen/
  54179. //
  54180. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  54181. //_______________________________________________________________
  54182. var BABYLON;
  54183. (function (BABYLON) {
  54184. var Internals;
  54185. (function (Internals) {
  54186. /**
  54187. * The bounding box information used during the conversion process.
  54188. */
  54189. var CMGBoundinBox = (function () {
  54190. function CMGBoundinBox() {
  54191. this.min = new BABYLON.Vector3(0, 0, 0);
  54192. this.max = new BABYLON.Vector3(0, 0, 0);
  54193. this.clear();
  54194. }
  54195. CMGBoundinBox.prototype.clear = function () {
  54196. this.min.x = CMGBoundinBox.MAX;
  54197. this.min.y = CMGBoundinBox.MAX;
  54198. this.min.z = CMGBoundinBox.MAX;
  54199. this.max.x = CMGBoundinBox.MIN;
  54200. this.max.y = CMGBoundinBox.MIN;
  54201. this.max.z = CMGBoundinBox.MIN;
  54202. };
  54203. CMGBoundinBox.prototype.augment = function (x, y, z) {
  54204. this.min.x = Math.min(this.min.x, x);
  54205. this.min.y = Math.min(this.min.y, y);
  54206. this.min.z = Math.min(this.min.z, z);
  54207. this.max.x = Math.max(this.max.x, x);
  54208. this.max.y = Math.max(this.max.y, y);
  54209. this.max.z = Math.max(this.max.z, z);
  54210. };
  54211. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  54212. this.min.x = Math.max(this.min.x, x);
  54213. this.min.y = Math.max(this.min.y, y);
  54214. this.min.z = Math.max(this.min.z, z);
  54215. };
  54216. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  54217. this.max.x = Math.min(this.max.x, x);
  54218. this.max.y = Math.min(this.max.y, y);
  54219. this.max.z = Math.min(this.max.z, z);
  54220. };
  54221. CMGBoundinBox.prototype.empty = function () {
  54222. if ((this.min.x > this.max.y) ||
  54223. (this.min.y > this.max.y) ||
  54224. (this.min.z > this.max.y)) {
  54225. return true;
  54226. }
  54227. else {
  54228. return false;
  54229. }
  54230. };
  54231. return CMGBoundinBox;
  54232. }());
  54233. CMGBoundinBox.MAX = Number.MAX_VALUE;
  54234. CMGBoundinBox.MIN = Number.MIN_VALUE;
  54235. /**
  54236. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  54237. * required by the glossinees of a material.
  54238. *
  54239. * This only supports the cosine drop power as well as Warp fixup generation method.
  54240. *
  54241. * This is using the process from CubeMapGen described here:
  54242. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  54243. */
  54244. var PMREMGenerator = (function () {
  54245. /**
  54246. * Constructor of the generator.
  54247. *
  54248. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  54249. * @param inputSize The size of the cubemap faces
  54250. * @param outputSize The size of the output cubemap faces
  54251. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  54252. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  54253. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  54254. * @param specularPower The max specular level of the desired cubemap
  54255. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  54256. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  54257. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  54258. */
  54259. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  54260. this.input = input;
  54261. this.inputSize = inputSize;
  54262. this.outputSize = outputSize;
  54263. this.maxNumMipLevels = maxNumMipLevels;
  54264. this.numChannels = numChannels;
  54265. this.isFloat = isFloat;
  54266. this.specularPower = specularPower;
  54267. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  54268. this.excludeBase = excludeBase;
  54269. this.fixup = fixup;
  54270. this._outputSurface = [];
  54271. this._numMipLevels = 0;
  54272. }
  54273. /**
  54274. * Launches the filter process and return the result.
  54275. *
  54276. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  54277. */
  54278. PMREMGenerator.prototype.filterCubeMap = function () {
  54279. // Init cubemap processor
  54280. this.init();
  54281. // Filters the cubemap
  54282. this.filterCubeMapMipChain();
  54283. // Returns the filtered mips.
  54284. return this._outputSurface;
  54285. };
  54286. PMREMGenerator.prototype.init = function () {
  54287. var i;
  54288. var j;
  54289. var mipLevelSize;
  54290. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  54291. if (this.maxNumMipLevels == 0) {
  54292. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  54293. }
  54294. //first miplevel size
  54295. mipLevelSize = this.outputSize;
  54296. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  54297. for (j = 0; j < this.maxNumMipLevels; j++) {
  54298. this._outputSurface.length++;
  54299. this._outputSurface[j] = [];
  54300. //Iterate over faces for output images
  54301. for (i = 0; i < 6; i++) {
  54302. this._outputSurface[j].length++;
  54303. // Initializes a new array for the output.
  54304. if (this.isFloat) {
  54305. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  54306. }
  54307. else {
  54308. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  54309. }
  54310. }
  54311. //next mip level is half size
  54312. mipLevelSize >>= 1;
  54313. this._numMipLevels++;
  54314. //terminate if mip chain becomes too small
  54315. if (mipLevelSize == 0) {
  54316. this.maxNumMipLevels = j;
  54317. return;
  54318. }
  54319. }
  54320. };
  54321. //--------------------------------------------------------------------------------------
  54322. //Cube map filtering and mip chain generation.
  54323. // the cube map filtereing is specified using a number of parameters:
  54324. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  54325. // indicates the region of the hemisphere to filter over for each tap.
  54326. //
  54327. // Note that the top mip level is also a filtered version of the original input images
  54328. // as well in order to create mip chains for diffuse environment illumination.
  54329. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  54330. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  54331. //
  54332. // Then the mip angle used to genreate the next level of the mip chain from the first level
  54333. // is a_InitialMipAngle
  54334. //
  54335. // The angle for the subsequent levels of the mip chain are specified by their parents
  54336. // filtering angle and a per-level scale and bias
  54337. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  54338. //
  54339. //--------------------------------------------------------------------------------------
  54340. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  54341. // First, take count of the lighting model to modify SpecularPower
  54342. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  54343. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  54344. //Cone angle start (for generating subsequent mip levels)
  54345. var currentSpecularPower = this.specularPower;
  54346. //Build filter lookup tables based on the source miplevel size
  54347. this.precomputeFilterLookupTables(this.inputSize);
  54348. // Note that we need to filter the first level before generating mipmap
  54349. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  54350. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  54351. // TODO : Write a function to copy and scale the base mipmap in output
  54352. // I am just lazy here and just put a high specular power value, and do some if.
  54353. if (this.excludeBase && (levelIndex == 0)) {
  54354. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  54355. currentSpecularPower = 100000.0;
  54356. }
  54357. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  54358. var srcCubeImage = this.input;
  54359. var dstCubeImage = this._outputSurface[levelIndex];
  54360. var dstSize = this.outputSize >> levelIndex;
  54361. // Compute required angle.
  54362. var angle = this.getBaseFilterAngle(currentSpecularPower);
  54363. // filter cube surfaces
  54364. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  54365. // fix seams
  54366. if (this.fixup) {
  54367. this.fixupCubeEdges(dstCubeImage, dstSize);
  54368. }
  54369. // Decrease the specular power to generate the mipmap chain
  54370. // TODO : Use another method for Exclude (see first comment at start of the function
  54371. if (this.excludeBase && (levelIndex == 0)) {
  54372. currentSpecularPower = this.specularPower;
  54373. }
  54374. currentSpecularPower *= this.cosinePowerDropPerMip;
  54375. }
  54376. };
  54377. //--------------------------------------------------------------------------------------
  54378. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  54379. // It allow to optimize the texel to access base on the specular power.
  54380. //--------------------------------------------------------------------------------------
  54381. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  54382. // We want to find the alpha such that:
  54383. // cos(alpha)^cosinePower = epsilon
  54384. // That's: acos(epsilon^(1/cosinePower))
  54385. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  54386. var angle = 180.0;
  54387. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  54388. angle *= 180.0 / Math.PI; // Convert to degree
  54389. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  54390. return angle;
  54391. };
  54392. //--------------------------------------------------------------------------------------
  54393. //Builds the following lookup tables prior to filtering:
  54394. // -normalizer cube map
  54395. // -tap weight lookup table
  54396. //
  54397. //--------------------------------------------------------------------------------------
  54398. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  54399. var srcTexelAngle;
  54400. var iCubeFace;
  54401. //clear pre-existing normalizer cube map
  54402. this._normCubeMap = [];
  54403. //Normalized vectors per cubeface and per-texel solid angle
  54404. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  54405. };
  54406. //--------------------------------------------------------------------------------------
  54407. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  54408. //
  54409. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  54410. //
  54411. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  54412. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  54413. // below
  54414. //--------------------------------------------------------------------------------------
  54415. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  54416. var iCubeFace;
  54417. var u;
  54418. var v;
  54419. //iterate over cube faces
  54420. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  54421. //First three channels for norm cube, and last channel for solid angle
  54422. this._normCubeMap.push(new Float32Array(size * size * 4));
  54423. //fast texture walk, build normalizer cube map
  54424. var facesData = this.input[iCubeFace];
  54425. for (v = 0; v < size; v++) {
  54426. for (u = 0; u < size; u++) {
  54427. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  54428. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  54429. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  54430. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  54431. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  54432. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  54433. }
  54434. }
  54435. }
  54436. };
  54437. //--------------------------------------------------------------------------------------
  54438. // Convert cubemap face texel coordinates and face idx to 3D vector
  54439. // note the U and V coords are integer coords and range from 0 to size-1
  54440. // this routine can be used to generate a normalizer cube map
  54441. //--------------------------------------------------------------------------------------
  54442. // SL BEGIN
  54443. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  54444. var nvcU;
  54445. var nvcV;
  54446. var tempVec;
  54447. // Change from original AMD code
  54448. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  54449. // + 0.5f is for texel center addressing
  54450. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  54451. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  54452. // warp fixup
  54453. if (fixup && size > 1) {
  54454. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  54455. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  54456. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  54457. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  54458. }
  54459. // Get current vector
  54460. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  54461. // U contribution
  54462. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  54463. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  54464. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  54465. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  54466. // V contribution and Sum
  54467. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  54468. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  54469. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  54470. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  54471. //add face axis
  54472. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  54473. PMREMGenerator._vectorTemp.x += faceAxis[0];
  54474. PMREMGenerator._vectorTemp.y += faceAxis[1];
  54475. PMREMGenerator._vectorTemp.z += faceAxis[2];
  54476. //normalize vector
  54477. PMREMGenerator._vectorTemp.normalize();
  54478. return PMREMGenerator._vectorTemp;
  54479. };
  54480. //--------------------------------------------------------------------------------------
  54481. // Convert 3D vector to cubemap face texel coordinates and face idx
  54482. // note the U and V coords are integer coords and range from 0 to size-1
  54483. // this routine can be used to generate a normalizer cube map
  54484. //
  54485. // returns face IDX and texel coords
  54486. //--------------------------------------------------------------------------------------
  54487. // SL BEGIN
  54488. /*
  54489. Mapping Texture Coordinates to Cube Map Faces
  54490. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  54491. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  54492. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  54493. map arrangement in Pixar's RenderMan package.
  54494. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  54495. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  54496. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  54497. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  54498. the major axis direction). The target column in the table below explains how the major axis direction
  54499. maps to the 2D image of a particular cube map target.
  54500. major axis
  54501. direction target sc tc ma
  54502. ---------- --------------------------------- --- --- ---
  54503. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  54504. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  54505. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  54506. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  54507. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  54508. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  54509. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  54510. an updated (s,t) is calculated as follows
  54511. s = ( sc/|ma| + 1 ) / 2
  54512. t = ( tc/|ma| + 1 ) / 2
  54513. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  54514. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  54515. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  54516. */
  54517. // Note this method return U and V in range from 0 to size-1
  54518. // SL END
  54519. // Store the information in vector3 for convenience (faceindex, u, v)
  54520. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  54521. var maxCoord;
  54522. var faceIdx;
  54523. //absolute value 3
  54524. var absX = Math.abs(x);
  54525. var absY = Math.abs(y);
  54526. var absZ = Math.abs(z);
  54527. if (absX >= absY && absX >= absZ) {
  54528. maxCoord = absX;
  54529. if (x >= 0) {
  54530. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  54531. }
  54532. else {
  54533. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  54534. }
  54535. }
  54536. else if (absY >= absX && absY >= absZ) {
  54537. maxCoord = absY;
  54538. if (y >= 0) {
  54539. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  54540. }
  54541. else {
  54542. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  54543. }
  54544. }
  54545. else {
  54546. maxCoord = absZ;
  54547. if (z >= 0) {
  54548. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  54549. }
  54550. else {
  54551. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  54552. }
  54553. }
  54554. //divide through by max coord so face vector lies on cube face
  54555. var scale = 1 / maxCoord;
  54556. x *= scale;
  54557. y *= scale;
  54558. z *= scale;
  54559. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  54560. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  54561. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  54562. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  54563. // Modify original AMD code to return value from 0 to Size - 1
  54564. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  54565. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  54566. PMREMGenerator._vectorTemp.x = faceIdx;
  54567. PMREMGenerator._vectorTemp.y = u;
  54568. PMREMGenerator._vectorTemp.z = v;
  54569. return PMREMGenerator._vectorTemp;
  54570. };
  54571. //--------------------------------------------------------------------------------------
  54572. //Original code from Ignacio CastaÒo
  54573. // This formula is from Manne ÷hrstrˆm's thesis.
  54574. // Take two coordiantes in the range [-1, 1] that define a portion of a
  54575. // cube face and return the area of the projection of that portion on the
  54576. // surface of the sphere.
  54577. //--------------------------------------------------------------------------------------
  54578. PMREMGenerator.prototype.areaElement = function (x, y) {
  54579. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  54580. };
  54581. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  54582. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  54583. // (+ 0.5f is for texel center addressing)
  54584. u = (2.0 * (u + 0.5) / size) - 1.0;
  54585. v = (2.0 * (v + 0.5) / size) - 1.0;
  54586. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  54587. var invResolution = 1.0 / size;
  54588. // U and V are the -1..1 texture coordinate on the current face.
  54589. // Get projected area for this texel
  54590. var x0 = u - invResolution;
  54591. var y0 = v - invResolution;
  54592. var x1 = u + invResolution;
  54593. var y1 = v + invResolution;
  54594. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  54595. return solidAngle;
  54596. };
  54597. //--------------------------------------------------------------------------------------
  54598. //The key to the speed of these filtering routines is to quickly define a per-face
  54599. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  54600. // Later these pixels are selectively processed based on their dot products to see if
  54601. // they reside within the filtering cone.
  54602. //
  54603. //This is done by computing the smallest per-texel angle to get a conservative estimate
  54604. // of the number of texels needed to be covered in width and height order to filter the
  54605. // region. the bounding box for the center taps face is defined first, and if the
  54606. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  54607. // defined next
  54608. //--------------------------------------------------------------------------------------
  54609. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  54610. // note that pixels within these regions may be rejected
  54611. // based on the anlge
  54612. var iCubeFace;
  54613. var u;
  54614. var v;
  54615. // bounding box per face to specify region to process
  54616. var filterExtents = [];
  54617. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  54618. filterExtents.push(new CMGBoundinBox());
  54619. }
  54620. // min angle a src texel can cover (in degrees)
  54621. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  54622. // angle about center tap to define filter cone
  54623. // filter angle is 1/2 the cone angle
  54624. var filterAngle = filterConeAngle / 2.0;
  54625. //ensure filter angle is larger than a texel
  54626. if (filterAngle < srcTexelAngle) {
  54627. filterAngle = srcTexelAngle;
  54628. }
  54629. //ensure filter cone is always smaller than the hemisphere
  54630. if (filterAngle > 90.0) {
  54631. filterAngle = 90.0;
  54632. }
  54633. // the maximum number of texels in 1D the filter cone angle will cover
  54634. // used to determine bounding box size for filter extents
  54635. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  54636. // ensure conservative region always covers at least one texel
  54637. if (filterSize < 1) {
  54638. filterSize = 1;
  54639. }
  54640. // dotProdThresh threshold based on cone angle to determine whether or not taps
  54641. // reside within the cone angle
  54642. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  54643. // process required faces
  54644. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  54645. //iterate over dst cube map face texel
  54646. for (v = 0; v < dstSize; v++) {
  54647. for (u = 0; u < dstSize; u++) {
  54648. //get center tap direction
  54649. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  54650. //clear old per-face filter extents
  54651. this.clearFilterExtents(filterExtents);
  54652. //define per-face filter extents
  54653. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  54654. //perform filtering of src faces using filter extents
  54655. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  54656. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  54657. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  54658. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  54659. }
  54660. }
  54661. }
  54662. };
  54663. //--------------------------------------------------------------------------------------
  54664. //Clear filter extents for the 6 cube map faces
  54665. //--------------------------------------------------------------------------------------
  54666. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  54667. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  54668. filterExtents[iCubeFaces].clear();
  54669. }
  54670. };
  54671. //--------------------------------------------------------------------------------------
  54672. //Define per-face bounding box filter extents
  54673. //
  54674. // These define conservative texel regions in each of the faces the filter can possibly
  54675. // process. When the pixels in the regions are actually processed, the dot product
  54676. // between the tap vector and the center tap vector is used to determine the weight of
  54677. // the tap and whether or not the tap is within the cone.
  54678. //
  54679. //--------------------------------------------------------------------------------------
  54680. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  54681. //neighboring face and bleed over amount, and width of BBOX for
  54682. // left, right, top, and bottom edges of this face
  54683. var bleedOverAmount = [0, 0, 0, 0];
  54684. var bleedOverBBoxMin = [0, 0, 0, 0];
  54685. var bleedOverBBoxMax = [0, 0, 0, 0];
  54686. var neighborFace;
  54687. var neighborEdge;
  54688. var oppositeFaceIdx;
  54689. //get face idx, and u, v info from center tap dir
  54690. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  54691. var faceIdx = result.x;
  54692. var u = result.y;
  54693. var v = result.z;
  54694. //define bbox size within face
  54695. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  54696. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  54697. filterExtents[faceIdx].clampMin(0, 0, 0);
  54698. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  54699. //u and v extent in face corresponding to center tap
  54700. var minU = filterExtents[faceIdx].min.x;
  54701. var minV = filterExtents[faceIdx].min.y;
  54702. var maxU = filterExtents[faceIdx].max.x;
  54703. var maxV = filterExtents[faceIdx].max.y;
  54704. //bleed over amounts for face across u=0 edge (left)
  54705. bleedOverAmount[0] = (bboxSize - u);
  54706. bleedOverBBoxMin[0] = minV;
  54707. bleedOverBBoxMax[0] = maxV;
  54708. //bleed over amounts for face across u=1 edge (right)
  54709. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  54710. bleedOverBBoxMin[1] = minV;
  54711. bleedOverBBoxMax[1] = maxV;
  54712. //bleed over to face across v=0 edge (up)
  54713. bleedOverAmount[2] = (bboxSize - v);
  54714. bleedOverBBoxMin[2] = minU;
  54715. bleedOverBBoxMax[2] = maxU;
  54716. //bleed over to face across v=1 edge (down)
  54717. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  54718. bleedOverBBoxMin[3] = minU;
  54719. bleedOverBBoxMax[3] = maxU;
  54720. //compute bleed over regions in neighboring faces
  54721. for (var i = 0; i < 4; i++) {
  54722. if (bleedOverAmount[i] > 0) {
  54723. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  54724. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  54725. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  54726. // be flipped: the cases are
  54727. // if a left edge mates with a left or bottom edge on the neighbor
  54728. // if a top edge mates with a top or right edge on the neighbor
  54729. // if a right edge mates with a right or top edge on the neighbor
  54730. // if a bottom edge mates with a bottom or left edge on the neighbor
  54731. //Seeing as the edges are enumerated as follows
  54732. // left =0
  54733. // right =1
  54734. // top =2
  54735. // bottom =3
  54736. //
  54737. // so if the edge enums are the same, or the sum of the enums == 3,
  54738. // the bbox needs to be flipped
  54739. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  54740. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  54741. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  54742. }
  54743. //The way the bounding box is extended onto the neighboring face
  54744. // depends on which edge of neighboring face abuts with this one
  54745. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  54746. case PMREMGenerator.CP_EDGE_LEFT:
  54747. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  54748. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  54749. break;
  54750. case PMREMGenerator.CP_EDGE_RIGHT:
  54751. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  54752. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  54753. break;
  54754. case PMREMGenerator.CP_EDGE_TOP:
  54755. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  54756. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  54757. break;
  54758. case PMREMGenerator.CP_EDGE_BOTTOM:
  54759. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  54760. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  54761. break;
  54762. }
  54763. //clamp filter extents in non-center tap faces to remain within surface
  54764. filterExtents[neighborFace].clampMin(0, 0, 0);
  54765. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  54766. }
  54767. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  54768. // from the center tap face, then process the opposite face entirely for now.
  54769. //Note that the cases in which this happens, what usually happens is that
  54770. // more than one edge bleeds onto the opposite face, and the bounding box
  54771. // encompasses the entire cube map face.
  54772. if (bleedOverAmount[i] > srcSize) {
  54773. //determine opposite face
  54774. switch (faceIdx) {
  54775. case PMREMGenerator.CP_FACE_X_POS:
  54776. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  54777. break;
  54778. case PMREMGenerator.CP_FACE_X_NEG:
  54779. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  54780. break;
  54781. case PMREMGenerator.CP_FACE_Y_POS:
  54782. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  54783. break;
  54784. case PMREMGenerator.CP_FACE_Y_NEG:
  54785. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  54786. break;
  54787. case PMREMGenerator.CP_FACE_Z_POS:
  54788. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  54789. break;
  54790. case PMREMGenerator.CP_FACE_Z_NEG:
  54791. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  54792. break;
  54793. default:
  54794. break;
  54795. }
  54796. //just encompass entire face for now
  54797. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  54798. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  54799. }
  54800. }
  54801. };
  54802. //--------------------------------------------------------------------------------------
  54803. //ProcessFilterExtents
  54804. // Process bounding box in each cube face
  54805. //
  54806. //--------------------------------------------------------------------------------------
  54807. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  54808. //accumulators are 64-bit floats in order to have the precision needed
  54809. // over a summation of a large number of pixels
  54810. var dstAccum = [0, 0, 0, 0];
  54811. var weightAccum = 0;
  54812. var k = 0;
  54813. var nSrcChannels = this.numChannels;
  54814. // norm cube map and srcCubeMap have same face width
  54815. var faceWidth = srcSize;
  54816. //amount to add to pointer to move to next scanline in images
  54817. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  54818. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  54819. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  54820. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  54821. // iterate over cubefaces
  54822. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  54823. //if bbox is non empty
  54824. if (!filterExtents[iFaceIdx].empty()) {
  54825. var uStart = filterExtents[iFaceIdx].min.x;
  54826. var vStart = filterExtents[iFaceIdx].min.y;
  54827. var uEnd = filterExtents[iFaceIdx].max.x;
  54828. var vEnd = filterExtents[iFaceIdx].max.y;
  54829. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  54830. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  54831. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  54832. for (var v = vStart; v <= vEnd; v++) {
  54833. var normCubeRowWalk = 0;
  54834. var srcCubeRowWalk = 0;
  54835. for (var u = uStart; u <= uEnd; u++) {
  54836. //pointer to direction in cube map associated with texel
  54837. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  54838. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  54839. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  54840. //check dot product to see if texel is within cone
  54841. var tapDotProd = texelVectX * centerTapDir.x +
  54842. texelVectY * centerTapDir.y +
  54843. texelVectZ * centerTapDir.z;
  54844. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  54845. //solid angle stored in 4th channel of normalizer/solid angle cube map
  54846. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  54847. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  54848. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  54849. // so just adding one to specularpower do the trick.
  54850. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  54851. //iterate over channels
  54852. for (k = 0; k < nSrcChannels; k++) {
  54853. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  54854. srcCubeRowWalk++;
  54855. }
  54856. weightAccum += weight; //accumulate weight
  54857. }
  54858. else {
  54859. //step across source pixel
  54860. srcCubeRowWalk += nSrcChannels;
  54861. }
  54862. normCubeRowWalk += 4; // 4 channels per norm cube map.
  54863. }
  54864. startIndexNormCubeMap += normCubePitch;
  54865. startIndexSrcCubeMap += srcCubePitch;
  54866. }
  54867. }
  54868. }
  54869. //divide through by weights if weight is non zero
  54870. if (weightAccum != 0.0) {
  54871. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  54872. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  54873. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  54874. if (this.numChannels > 3) {
  54875. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  54876. }
  54877. }
  54878. else {
  54879. // otherwise sample nearest
  54880. // get face idx and u, v texel coordinate in face
  54881. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  54882. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  54883. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  54884. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  54885. if (this.numChannels > 3) {
  54886. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  54887. }
  54888. }
  54889. return PMREMGenerator._vectorTemp;
  54890. };
  54891. //--------------------------------------------------------------------------------------
  54892. // Fixup cube edges
  54893. //
  54894. // average texels on cube map faces across the edges
  54895. // WARP/BENT Method Only.
  54896. //--------------------------------------------------------------------------------------
  54897. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  54898. var k;
  54899. var j;
  54900. var i;
  54901. var iFace;
  54902. var iCorner = 0;
  54903. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  54904. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  54905. // note that if functionality to filter across the three texels for each corner, then
  54906. //indexed by corner and face idx. the array contains the face the start points belongs to.
  54907. var cornerPtr = [
  54908. [[], [], []],
  54909. [[], [], []],
  54910. [[], [], []],
  54911. [[], [], []],
  54912. [[], [], []],
  54913. [[], [], []],
  54914. [[], [], []],
  54915. [[], [], []]
  54916. ];
  54917. //if there is no fixup, or fixup width = 0, do nothing
  54918. if (cubeMapSize < 1) {
  54919. return;
  54920. }
  54921. //special case 1x1 cubemap, average face colors
  54922. if (cubeMapSize == 1) {
  54923. //iterate over channels
  54924. for (k = 0; k < this.numChannels; k++) {
  54925. var accum = 0.0;
  54926. //iterate over faces to accumulate face colors
  54927. for (iFace = 0; iFace < 6; iFace++) {
  54928. accum += cubeMap[iFace][k];
  54929. }
  54930. //compute average over 6 face colors
  54931. accum /= 6.0;
  54932. //iterate over faces to distribute face colors
  54933. for (iFace = 0; iFace < 6; iFace++) {
  54934. cubeMap[iFace][k] = accum;
  54935. }
  54936. }
  54937. return;
  54938. }
  54939. //iterate over faces to collect list of corner texel pointers
  54940. for (iFace = 0; iFace < 6; iFace++) {
  54941. //the 4 corner pointers for this face
  54942. faceCornerStartIndicies[0] = [iFace, 0];
  54943. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  54944. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  54945. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  54946. //iterate over face corners to collect cube corner pointers
  54947. for (iCorner = 0; iCorner < 4; iCorner++) {
  54948. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  54949. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  54950. cornerNumPtrs[corner]++;
  54951. }
  54952. }
  54953. //iterate over corners to average across corner tap values
  54954. for (iCorner = 0; iCorner < 8; iCorner++) {
  54955. for (k = 0; k < this.numChannels; k++) {
  54956. var cornerTapAccum = 0.0;
  54957. //iterate over corner texels and average results
  54958. for (i = 0; i < 3; i++) {
  54959. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  54960. }
  54961. //divide by 3 to compute average of corner tap values
  54962. cornerTapAccum *= (1.0 / 3.0);
  54963. //iterate over corner texels and average results
  54964. for (i = 0; i < 3; i++) {
  54965. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  54966. }
  54967. }
  54968. }
  54969. //iterate over the twelve edges of the cube to average across edges
  54970. for (i = 0; i < 12; i++) {
  54971. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  54972. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  54973. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  54974. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  54975. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  54976. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  54977. var edgeWalk = 0;
  54978. var neighborEdgeWalk = 0;
  54979. //Determine walking pointers based on edge type
  54980. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  54981. switch (edge) {
  54982. case PMREMGenerator.CP_EDGE_LEFT:
  54983. // no change to faceEdgeStartPtr
  54984. edgeWalk = this.numChannels * cubeMapSize;
  54985. break;
  54986. case PMREMGenerator.CP_EDGE_RIGHT:
  54987. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54988. edgeWalk = this.numChannels * cubeMapSize;
  54989. break;
  54990. case PMREMGenerator.CP_EDGE_TOP:
  54991. // no change to faceEdgeStartPtr
  54992. edgeWalk = this.numChannels;
  54993. break;
  54994. case PMREMGenerator.CP_EDGE_BOTTOM:
  54995. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  54996. edgeWalk = this.numChannels;
  54997. break;
  54998. }
  54999. //For certain types of edge abutments, the neighbor edge walk needs to
  55000. // be flipped: the cases are
  55001. // if a left edge mates with a left or bottom edge on the neighbor
  55002. // if a top edge mates with a top or right edge on the neighbor
  55003. // if a right edge mates with a right or top edge on the neighbor
  55004. // if a bottom edge mates with a bottom or left edge on the neighbor
  55005. //Seeing as the edges are enumerated as follows
  55006. // left =0
  55007. // right =1
  55008. // top =2
  55009. // bottom =3
  55010. //
  55011. //If the edge enums are the same, or the sum of the enums == 3,
  55012. // the neighbor edge walk needs to be flipped
  55013. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  55014. switch (neighborEdge) {
  55015. case PMREMGenerator.CP_EDGE_LEFT:
  55016. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  55017. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  55018. break;
  55019. case PMREMGenerator.CP_EDGE_RIGHT:
  55020. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  55021. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  55022. break;
  55023. case PMREMGenerator.CP_EDGE_TOP:
  55024. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  55025. neighborEdgeWalk = -this.numChannels;
  55026. break;
  55027. case PMREMGenerator.CP_EDGE_BOTTOM:
  55028. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  55029. neighborEdgeWalk = -this.numChannels;
  55030. break;
  55031. }
  55032. }
  55033. else {
  55034. //swapped direction neighbor edge walk
  55035. switch (neighborEdge) {
  55036. case PMREMGenerator.CP_EDGE_LEFT:
  55037. //no change to neighborEdgeStartPtr for this case since it points
  55038. // to the upper left corner already
  55039. neighborEdgeWalk = this.numChannels * cubeMapSize;
  55040. break;
  55041. case PMREMGenerator.CP_EDGE_RIGHT:
  55042. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  55043. neighborEdgeWalk = this.numChannels * cubeMapSize;
  55044. break;
  55045. case PMREMGenerator.CP_EDGE_TOP:
  55046. //no change to neighborEdgeStartPtr for this case since it points
  55047. // to the upper left corner already
  55048. neighborEdgeWalk = this.numChannels;
  55049. break;
  55050. case PMREMGenerator.CP_EDGE_BOTTOM:
  55051. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  55052. neighborEdgeWalk = this.numChannels;
  55053. break;
  55054. }
  55055. }
  55056. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  55057. //nearby neighborhood
  55058. //step ahead one texel on edge
  55059. edgeStartIndex += edgeWalk;
  55060. neighborEdgeStartIndex += neighborEdgeWalk;
  55061. // note that this loop does not process the corner texels, since they have already been
  55062. // averaged across faces across earlier
  55063. for (j = 1; j < (cubeMapSize - 1); j++) {
  55064. //for each set of taps along edge, average them
  55065. // and rewrite the results into the edges
  55066. for (k = 0; k < this.numChannels; k++) {
  55067. var edgeTap = cubeMap[face][edgeStartIndex + k];
  55068. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  55069. //compute average of tap intensity values
  55070. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  55071. //propagate average of taps to edge taps
  55072. cubeMap[face][edgeStartIndex + k] = avgTap;
  55073. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  55074. }
  55075. edgeStartIndex += edgeWalk;
  55076. neighborEdgeStartIndex += neighborEdgeWalk;
  55077. }
  55078. }
  55079. };
  55080. return PMREMGenerator;
  55081. }());
  55082. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  55083. PMREMGenerator.CP_UDIR = 0;
  55084. PMREMGenerator.CP_VDIR = 1;
  55085. PMREMGenerator.CP_FACEAXIS = 2;
  55086. //used to index cube faces
  55087. PMREMGenerator.CP_FACE_X_POS = 0;
  55088. PMREMGenerator.CP_FACE_X_NEG = 1;
  55089. PMREMGenerator.CP_FACE_Y_POS = 2;
  55090. PMREMGenerator.CP_FACE_Y_NEG = 3;
  55091. PMREMGenerator.CP_FACE_Z_POS = 4;
  55092. PMREMGenerator.CP_FACE_Z_NEG = 5;
  55093. //used to index image edges
  55094. // NOTE.. the actual number corresponding to the edge is important
  55095. // do not change these, or the code will break
  55096. //
  55097. // CP_EDGE_LEFT is u = 0
  55098. // CP_EDGE_RIGHT is u = width-1
  55099. // CP_EDGE_TOP is v = 0
  55100. // CP_EDGE_BOTTOM is v = height-1
  55101. PMREMGenerator.CP_EDGE_LEFT = 0;
  55102. PMREMGenerator.CP_EDGE_RIGHT = 1;
  55103. PMREMGenerator.CP_EDGE_TOP = 2;
  55104. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  55105. //corners of CUBE map (P or N specifys if it corresponds to the
  55106. // positive or negative direction each of X, Y, and Z
  55107. PMREMGenerator.CP_CORNER_NNN = 0;
  55108. PMREMGenerator.CP_CORNER_NNP = 1;
  55109. PMREMGenerator.CP_CORNER_NPN = 2;
  55110. PMREMGenerator.CP_CORNER_NPP = 3;
  55111. PMREMGenerator.CP_CORNER_PNN = 4;
  55112. PMREMGenerator.CP_CORNER_PNP = 5;
  55113. PMREMGenerator.CP_CORNER_PPN = 6;
  55114. PMREMGenerator.CP_CORNER_PPP = 7;
  55115. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  55116. //3x2 matrices that map cube map indexing vectors in 3d
  55117. // (after face selection and divide through by the
  55118. // _ABSOLUTE VALUE_ of the max coord)
  55119. // into NVC space
  55120. //Note this currently assumes the D3D cube face ordering and orientation
  55121. PMREMGenerator._sgFace2DMapping = [
  55122. //XPOS face
  55123. [[0, 0, -1],
  55124. [0, -1, 0],
  55125. [1, 0, 0]],
  55126. //XNEG face
  55127. [[0, 0, 1],
  55128. [0, -1, 0],
  55129. [-1, 0, 0]],
  55130. //YPOS face
  55131. [[1, 0, 0],
  55132. [0, 0, 1],
  55133. [0, 1, 0]],
  55134. //YNEG face
  55135. [[1, 0, 0],
  55136. [0, 0, -1],
  55137. [0, -1, 0]],
  55138. //ZPOS face
  55139. [[1, 0, 0],
  55140. [0, -1, 0],
  55141. [0, 0, 1]],
  55142. //ZNEG face
  55143. [[-1, 0, 0],
  55144. [0, -1, 0],
  55145. [0, 0, -1]],
  55146. ];
  55147. //------------------------------------------------------------------------------
  55148. // D3D cube map face specification
  55149. // mapping from 3D x,y,z cube map lookup coordinates
  55150. // to 2D within face u,v coordinates
  55151. //
  55152. // --------------------> U direction
  55153. // | (within-face texture space)
  55154. // | _____
  55155. // | | |
  55156. // | | +Y |
  55157. // | _____|_____|_____ _____
  55158. // | | | | | |
  55159. // | | -X | +Z | +X | -Z |
  55160. // | |_____|_____|_____|_____|
  55161. // | | |
  55162. // | | -Y |
  55163. // | |_____|
  55164. // |
  55165. // v V direction
  55166. // (within-face texture space)
  55167. //------------------------------------------------------------------------------
  55168. //Information about neighbors and how texture coorrdinates change across faces
  55169. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  55170. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  55171. //Note this currently assumes the D3D cube face ordering and orientation
  55172. PMREMGenerator._sgCubeNgh = [
  55173. //XPOS face
  55174. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55175. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  55176. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55177. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  55178. //XNEG face
  55179. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  55180. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  55181. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  55182. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  55183. //YPOS face
  55184. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  55185. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  55186. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  55187. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  55188. //YNEG face
  55189. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  55190. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55191. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55192. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  55193. //ZPOS face
  55194. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  55195. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  55196. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55197. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  55198. //ZNEG face
  55199. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55200. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  55201. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  55202. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  55203. ];
  55204. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  55205. // this table is used to average over the edges.
  55206. PMREMGenerator._sgCubeEdgeList = [
  55207. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  55208. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55209. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  55210. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55211. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  55212. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  55213. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  55214. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  55215. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  55216. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55217. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  55218. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  55219. ];
  55220. //Information about which of the 8 cube corners are correspond to the
  55221. // the 4 corners in each cube face
  55222. // the order is upper left, upper right, lower left, lower right
  55223. PMREMGenerator._sgCubeCornerList = [
  55224. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  55225. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  55226. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  55227. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  55228. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  55229. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  55230. ];
  55231. Internals.PMREMGenerator = PMREMGenerator;
  55232. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55233. })(BABYLON || (BABYLON = {}));
  55234. //# sourceMappingURL=babylon.pmremgenerator.js.map
  55235. var BABYLON;
  55236. (function (BABYLON) {
  55237. /**
  55238. * This represents a texture coming from an HDR input.
  55239. *
  55240. * The only supported format is currently panorama picture stored in RGBE format.
  55241. * Example of such files can be found on HDRLib: http://hdrlib.com/
  55242. */
  55243. var HDRCubeTexture = (function (_super) {
  55244. __extends(HDRCubeTexture, _super);
  55245. /**
  55246. * Instantiates an HDRTexture from the following parameters.
  55247. *
  55248. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  55249. * @param scene The scene the texture will be used in
  55250. * @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.
  55251. * @param noMipmap Forces to not generate the mipmap if true
  55252. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  55253. * @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)
  55254. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  55255. */
  55256. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  55257. if (noMipmap === void 0) { noMipmap = false; }
  55258. if (generateHarmonics === void 0) { generateHarmonics = true; }
  55259. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  55260. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  55261. if (onLoad === void 0) { onLoad = null; }
  55262. if (onError === void 0) { onError = null; }
  55263. var _this = _super.call(this, scene) || this;
  55264. _this._useInGammaSpace = false;
  55265. _this._generateHarmonics = true;
  55266. _this._isBABYLONPreprocessed = false;
  55267. _this._onLoad = null;
  55268. _this._onError = null;
  55269. /**
  55270. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  55271. */
  55272. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  55273. /**
  55274. * The spherical polynomial data extracted from the texture.
  55275. */
  55276. _this.sphericalPolynomial = null;
  55277. /**
  55278. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  55279. * This is usefull at run time to apply the good shader.
  55280. */
  55281. _this.isPMREM = false;
  55282. _this._isBlocking = true;
  55283. if (!url) {
  55284. return _this;
  55285. }
  55286. _this.name = url;
  55287. _this.url = url;
  55288. _this.hasAlpha = false;
  55289. _this.isCube = true;
  55290. _this._textureMatrix = BABYLON.Matrix.Identity();
  55291. _this._onLoad = onLoad;
  55292. _this._onError = onError;
  55293. if (size) {
  55294. _this._isBABYLONPreprocessed = false;
  55295. _this._noMipmap = noMipmap;
  55296. _this._size = size;
  55297. _this._useInGammaSpace = useInGammaSpace;
  55298. _this._usePMREMGenerator = usePMREMGenerator &&
  55299. scene.getEngine().getCaps().textureLOD &&
  55300. _this.getScene().getEngine().getCaps().textureFloat &&
  55301. !_this._useInGammaSpace;
  55302. }
  55303. else {
  55304. _this._isBABYLONPreprocessed = true;
  55305. _this._noMipmap = false;
  55306. _this._useInGammaSpace = false;
  55307. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  55308. _this.getScene().getEngine().getCaps().textureFloat &&
  55309. !_this._useInGammaSpace;
  55310. }
  55311. _this.isPMREM = _this._usePMREMGenerator;
  55312. _this._texture = _this._getFromCache(url, _this._noMipmap);
  55313. if (!_this._texture) {
  55314. if (!scene.useDelayedTextureLoading) {
  55315. _this.loadTexture();
  55316. }
  55317. else {
  55318. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55319. }
  55320. }
  55321. return _this;
  55322. }
  55323. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  55324. /**
  55325. * Gets wether or not the texture is blocking during loading.
  55326. */
  55327. get: function () {
  55328. return this._isBlocking;
  55329. },
  55330. /**
  55331. * Sets wether or not the texture is blocking during loading.
  55332. */
  55333. set: function (value) {
  55334. this._isBlocking = value;
  55335. },
  55336. enumerable: true,
  55337. configurable: true
  55338. });
  55339. /**
  55340. * Occurs when the file is a preprocessed .babylon.hdr file.
  55341. */
  55342. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  55343. var _this = this;
  55344. var mipLevels = 0;
  55345. var floatArrayView = null;
  55346. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  55347. var mips = [];
  55348. var startIndex = 30;
  55349. for (var level = 0; level < mipLevels; level++) {
  55350. mips.push([]);
  55351. // Fill each pixel of the mip level.
  55352. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  55353. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55354. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  55355. mips[level].push(faceData);
  55356. startIndex += faceSize;
  55357. }
  55358. }
  55359. return mips;
  55360. } : null;
  55361. var callback = function (buffer) {
  55362. // Create Native Array Views
  55363. var intArrayView = new Int32Array(buffer);
  55364. floatArrayView = new Float32Array(buffer);
  55365. // Fill header.
  55366. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  55367. _this._size = intArrayView[1]; // CubeMap max mip face size.
  55368. // Update Texture Information.
  55369. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  55370. // Fill polynomial information.
  55371. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  55372. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  55373. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  55374. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  55375. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  55376. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  55377. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  55378. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  55379. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  55380. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  55381. // Fill pixel data.
  55382. mipLevels = intArrayView[29]; // Number of mip levels.
  55383. var startIndex = 30;
  55384. var data = [];
  55385. var faceSize = Math.pow(_this._size, 2) * 3;
  55386. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55387. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  55388. startIndex += faceSize;
  55389. }
  55390. var results = [];
  55391. var byteArray = null;
  55392. // Push each faces.
  55393. for (var k = 0; k < 6; k++) {
  55394. var dataFace = null;
  55395. // If special cases.
  55396. if (!mipmapGenerator) {
  55397. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  55398. dataFace = data[j];
  55399. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  55400. // 3 channels of 1 bytes per pixel in bytes.
  55401. var byteBuffer = new ArrayBuffer(faceSize);
  55402. byteArray = new Uint8Array(byteBuffer);
  55403. }
  55404. for (var i = 0; i < _this._size * _this._size; i++) {
  55405. // Put in gamma space if requested.
  55406. if (_this._useInGammaSpace) {
  55407. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  55408. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  55409. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  55410. }
  55411. // Convert to int texture for fallback.
  55412. if (byteArray) {
  55413. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  55414. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  55415. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  55416. // May use luminance instead if the result is not accurate.
  55417. var max = Math.max(Math.max(r, g), b);
  55418. if (max > 255) {
  55419. var scale = 255 / max;
  55420. r *= scale;
  55421. g *= scale;
  55422. b *= scale;
  55423. }
  55424. byteArray[(i * 3) + 0] = r;
  55425. byteArray[(i * 3) + 1] = g;
  55426. byteArray[(i * 3) + 2] = b;
  55427. }
  55428. }
  55429. }
  55430. else {
  55431. dataFace = data[k];
  55432. }
  55433. // Fill the array accordingly.
  55434. if (byteArray) {
  55435. results.push(byteArray);
  55436. }
  55437. else {
  55438. results.push(dataFace);
  55439. }
  55440. }
  55441. return results;
  55442. };
  55443. 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);
  55444. };
  55445. /**
  55446. * Occurs when the file is raw .hdr file.
  55447. */
  55448. HDRCubeTexture.prototype.loadHDRTexture = function () {
  55449. var _this = this;
  55450. var callback = function (buffer) {
  55451. // Extract the raw linear data.
  55452. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  55453. // Generate harmonics if needed.
  55454. if (_this._generateHarmonics) {
  55455. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  55456. }
  55457. var results = [];
  55458. var byteArray = null;
  55459. // Push each faces.
  55460. for (var j = 0; j < 6; j++) {
  55461. // Create uintarray fallback.
  55462. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  55463. // 3 channels of 1 bytes per pixel in bytes.
  55464. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  55465. byteArray = new Uint8Array(byteBuffer);
  55466. }
  55467. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  55468. // If special cases.
  55469. if (_this._useInGammaSpace || byteArray) {
  55470. for (var i = 0; i < _this._size * _this._size; i++) {
  55471. // Put in gamma space if requested.
  55472. if (_this._useInGammaSpace) {
  55473. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  55474. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  55475. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  55476. }
  55477. // Convert to int texture for fallback.
  55478. if (byteArray) {
  55479. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  55480. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  55481. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  55482. // May use luminance instead if the result is not accurate.
  55483. var max = Math.max(Math.max(r, g), b);
  55484. if (max > 255) {
  55485. var scale = 255 / max;
  55486. r *= scale;
  55487. g *= scale;
  55488. b *= scale;
  55489. }
  55490. byteArray[(i * 3) + 0] = r;
  55491. byteArray[(i * 3) + 1] = g;
  55492. byteArray[(i * 3) + 2] = b;
  55493. }
  55494. }
  55495. }
  55496. if (byteArray) {
  55497. results.push(byteArray);
  55498. }
  55499. else {
  55500. results.push(dataFace);
  55501. }
  55502. }
  55503. return results;
  55504. };
  55505. var mipmapGenerator = null;
  55506. if (!this._noMipmap &&
  55507. this._usePMREMGenerator) {
  55508. mipmapGenerator = function (data) {
  55509. // Custom setup of the generator matching with the PBR shader values.
  55510. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  55511. return generator.filterCubeMap();
  55512. };
  55513. }
  55514. 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);
  55515. };
  55516. /**
  55517. * Starts the loading process of the texture.
  55518. */
  55519. HDRCubeTexture.prototype.loadTexture = function () {
  55520. if (this._isBABYLONPreprocessed) {
  55521. this.loadBabylonTexture();
  55522. }
  55523. else {
  55524. this.loadHDRTexture();
  55525. }
  55526. };
  55527. HDRCubeTexture.prototype.clone = function () {
  55528. var size = this._isBABYLONPreprocessed ? null : this._size;
  55529. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  55530. // Base texture
  55531. newTexture.level = this.level;
  55532. newTexture.wrapU = this.wrapU;
  55533. newTexture.wrapV = this.wrapV;
  55534. newTexture.coordinatesIndex = this.coordinatesIndex;
  55535. newTexture.coordinatesMode = this.coordinatesMode;
  55536. return newTexture;
  55537. };
  55538. // Methods
  55539. HDRCubeTexture.prototype.delayLoad = function () {
  55540. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55541. return;
  55542. }
  55543. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55544. this._texture = this._getFromCache(this.url, this._noMipmap);
  55545. if (!this._texture) {
  55546. this.loadTexture();
  55547. }
  55548. };
  55549. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  55550. return this._textureMatrix;
  55551. };
  55552. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  55553. var texture = null;
  55554. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  55555. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  55556. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  55557. texture.name = parsedTexture.name;
  55558. texture.hasAlpha = parsedTexture.hasAlpha;
  55559. texture.level = parsedTexture.level;
  55560. texture.coordinatesMode = parsedTexture.coordinatesMode;
  55561. texture.isBlocking = parsedTexture.isBlocking;
  55562. }
  55563. return texture;
  55564. };
  55565. HDRCubeTexture.prototype.serialize = function () {
  55566. if (!this.name) {
  55567. return null;
  55568. }
  55569. var serializationObject = {};
  55570. serializationObject.name = this.name;
  55571. serializationObject.hasAlpha = this.hasAlpha;
  55572. serializationObject.isCube = true;
  55573. serializationObject.level = this.level;
  55574. serializationObject.size = this._size;
  55575. serializationObject.coordinatesMode = this.coordinatesMode;
  55576. serializationObject.useInGammaSpace = this._useInGammaSpace;
  55577. serializationObject.generateHarmonics = this._generateHarmonics;
  55578. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  55579. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  55580. serializationObject.customType = "BABYLON.HDRCubeTexture";
  55581. serializationObject.noMipmap = this._noMipmap;
  55582. serializationObject.isBlocking = this._isBlocking;
  55583. return serializationObject;
  55584. };
  55585. /**
  55586. * Saves as a file the data contained in the texture in a binary format.
  55587. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  55588. * as the spherical used in the lighting.
  55589. * @param url The HDR file url.
  55590. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  55591. * @param onError Method called if any error happens during download.
  55592. * @return The packed binary data.
  55593. */
  55594. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  55595. if (onError === void 0) { onError = null; }
  55596. var callback = function (buffer) {
  55597. var data = new Blob([buffer], { type: 'application/octet-stream' });
  55598. // Returns a URL you can use as a href.
  55599. var objUrl = window.URL.createObjectURL(data);
  55600. // Simulates a link to it and click to dowload.
  55601. var a = document.createElement("a");
  55602. document.body.appendChild(a);
  55603. a.style.display = "none";
  55604. a.href = objUrl;
  55605. a.download = "envmap.babylon.hdr";
  55606. a.click();
  55607. };
  55608. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  55609. };
  55610. /**
  55611. * Serializes the data contained in the texture in a binary format.
  55612. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  55613. * as the spherical used in the lighting.
  55614. * @param url The HDR file url.
  55615. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  55616. * @param onError Method called if any error happens during download.
  55617. * @return The packed binary data.
  55618. */
  55619. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  55620. if (onError === void 0) { onError = null; }
  55621. // Needs the url tho create the texture.
  55622. if (!url) {
  55623. return null;
  55624. }
  55625. // Check Power of two size.
  55626. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  55627. return null;
  55628. }
  55629. var getDataCallback = function (dataBuffer) {
  55630. // Extract the raw linear data.
  55631. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  55632. // Generate harmonics if needed.
  55633. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  55634. // Generate seamless faces
  55635. var mipGeneratorArray = [];
  55636. // Data are known to be in +X +Y +Z -X -Y -Z
  55637. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  55638. mipGeneratorArray.push(cubeData.right); // +X
  55639. mipGeneratorArray.push(cubeData.left); // -X
  55640. mipGeneratorArray.push(cubeData.up); // +Y
  55641. mipGeneratorArray.push(cubeData.down); // -Y
  55642. mipGeneratorArray.push(cubeData.front); // +Z
  55643. mipGeneratorArray.push(cubeData.back); // -Z
  55644. // Custom setup of the generator matching with the PBR shader values.
  55645. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  55646. var mippedData = generator.filterCubeMap();
  55647. // Compute required byte length.
  55648. var byteLength = 1 * 4; // Raw Data Version int32.
  55649. byteLength += 4; // CubeMap max mip face size int32.
  55650. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  55651. // Add data size.
  55652. byteLength += 4; // Number of mip levels int32.
  55653. for (var level = 0; level < mippedData.length; level++) {
  55654. var mipSize = size >> level;
  55655. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  55656. }
  55657. // Prepare binary structure.
  55658. var buffer = new ArrayBuffer(byteLength);
  55659. var intArrayView = new Int32Array(buffer);
  55660. var floatArrayView = new Float32Array(buffer);
  55661. // Fill header.
  55662. intArrayView[0] = 1; // Version 1.
  55663. intArrayView[1] = size; // CubeMap max mip face size.
  55664. // Fill polynomial information.
  55665. sphericalPolynomial.x.toArray(floatArrayView, 2);
  55666. sphericalPolynomial.y.toArray(floatArrayView, 5);
  55667. sphericalPolynomial.z.toArray(floatArrayView, 8);
  55668. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  55669. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  55670. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  55671. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  55672. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  55673. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  55674. // Fill pixel data.
  55675. intArrayView[29] = mippedData.length; // Number of mip levels.
  55676. var startIndex = 30;
  55677. for (var level = 0; level < mippedData.length; level++) {
  55678. // Fill each pixel of the mip level.
  55679. var faceSize = Math.pow(size >> level, 2) * 3;
  55680. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55681. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  55682. startIndex += faceSize;
  55683. }
  55684. }
  55685. // Callback.
  55686. callback(buffer);
  55687. };
  55688. // Download and process.
  55689. BABYLON.Tools.LoadFile(url, function (data) {
  55690. getDataCallback(data);
  55691. }, null, null, true, onError);
  55692. };
  55693. return HDRCubeTexture;
  55694. }(BABYLON.BaseTexture));
  55695. HDRCubeTexture._facesMapping = [
  55696. "right",
  55697. "up",
  55698. "front",
  55699. "left",
  55700. "down",
  55701. "back"
  55702. ];
  55703. BABYLON.HDRCubeTexture = HDRCubeTexture;
  55704. })(BABYLON || (BABYLON = {}));
  55705. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  55706. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  55707. // Huge respect for a such great lib.
  55708. // Earcut license:
  55709. // Copyright (c) 2016, Mapbox
  55710. //
  55711. // Permission to use, copy, modify, and/or distribute this software for any purpose
  55712. // with or without fee is hereby granted, provided that the above copyright notice
  55713. // and this permission notice appear in all copies.
  55714. //
  55715. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  55716. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  55717. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  55718. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  55719. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  55720. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  55721. // THIS SOFTWARE.
  55722. var Earcut;
  55723. (function (Earcut) {
  55724. /**
  55725. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  55726. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  55727. * @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).
  55728. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  55729. */
  55730. function earcut(data, holeIndices, dim) {
  55731. dim = dim || 2;
  55732. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  55733. if (!outerNode)
  55734. return triangles;
  55735. var minX, minY, maxX, maxY, x, y, size;
  55736. if (hasHoles)
  55737. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  55738. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  55739. if (data.length > 80 * dim) {
  55740. minX = maxX = data[0];
  55741. minY = maxY = data[1];
  55742. for (var i = dim; i < outerLen; i += dim) {
  55743. x = data[i];
  55744. y = data[i + 1];
  55745. if (x < minX)
  55746. minX = x;
  55747. if (y < minY)
  55748. minY = y;
  55749. if (x > maxX)
  55750. maxX = x;
  55751. if (y > maxY)
  55752. maxY = y;
  55753. }
  55754. // minX, minY and size are later used to transform coords into integers for z-order calculation
  55755. size = Math.max(maxX - minX, maxY - minY);
  55756. }
  55757. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  55758. return triangles;
  55759. }
  55760. Earcut.earcut = earcut;
  55761. // create a circular doubly linked list from polygon points in the specified winding order
  55762. function linkedList(data, start, end, dim, clockwise) {
  55763. var i, last;
  55764. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  55765. for (i = start; i < end; i += dim)
  55766. last = insertNode(i, data[i], data[i + 1], last);
  55767. }
  55768. else {
  55769. for (i = end - dim; i >= start; i -= dim)
  55770. last = insertNode(i, data[i], data[i + 1], last);
  55771. }
  55772. if (last && equals(last, last.next)) {
  55773. removeNode(last);
  55774. last = last.next;
  55775. }
  55776. return last;
  55777. }
  55778. // eliminate colinear or duplicate points
  55779. function filterPoints(start, end) {
  55780. if (!start)
  55781. return start;
  55782. if (!end)
  55783. end = start;
  55784. var p = start, again;
  55785. do {
  55786. again = false;
  55787. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  55788. removeNode(p);
  55789. p = end = p.prev;
  55790. if (p === p.next)
  55791. return null;
  55792. again = true;
  55793. }
  55794. else {
  55795. p = p.next;
  55796. }
  55797. } while (again || p !== end);
  55798. return end;
  55799. }
  55800. // main ear slicing loop which triangulates a polygon (given as a linked list)
  55801. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  55802. if (!ear)
  55803. return;
  55804. // interlink polygon nodes in z-order
  55805. if (!pass && size)
  55806. indexCurve(ear, minX, minY, size);
  55807. var stop = ear, prev, next;
  55808. // iterate through ears, slicing them one by one
  55809. while (ear.prev !== ear.next) {
  55810. prev = ear.prev;
  55811. next = ear.next;
  55812. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  55813. // cut off the triangle
  55814. triangles.push(prev.i / dim);
  55815. triangles.push(ear.i / dim);
  55816. triangles.push(next.i / dim);
  55817. removeNode(ear);
  55818. // skipping the next vertice leads to less sliver triangles
  55819. ear = next.next;
  55820. stop = next.next;
  55821. continue;
  55822. }
  55823. ear = next;
  55824. // if we looped through the whole remaining polygon and can't find any more ears
  55825. if (ear === stop) {
  55826. // try filtering points and slicing again
  55827. if (!pass) {
  55828. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  55829. // if this didn't work, try curing all small self-intersections locally
  55830. }
  55831. else if (pass === 1) {
  55832. ear = cureLocalIntersections(ear, triangles, dim);
  55833. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  55834. // as a last resort, try splitting the remaining polygon into two
  55835. }
  55836. else if (pass === 2) {
  55837. splitEarcut(ear, triangles, dim, minX, minY, size);
  55838. }
  55839. break;
  55840. }
  55841. }
  55842. }
  55843. // check whether a polygon node forms a valid ear with adjacent nodes
  55844. function isEar(ear) {
  55845. var a = ear.prev, b = ear, c = ear.next;
  55846. if (area(a, b, c) >= 0)
  55847. return false; // reflex, can't be an ear
  55848. // now make sure we don't have other points inside the potential ear
  55849. var p = ear.next.next;
  55850. while (p !== ear.prev) {
  55851. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  55852. area(p.prev, p, p.next) >= 0)
  55853. return false;
  55854. p = p.next;
  55855. }
  55856. return true;
  55857. }
  55858. function isEarHashed(ear, minX, minY, size) {
  55859. var a = ear.prev, b = ear, c = ear.next;
  55860. if (area(a, b, c) >= 0)
  55861. return false; // reflex, can't be an ear
  55862. // triangle bbox; min & max are calculated like this for speed
  55863. 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);
  55864. // z-order range for the current triangle bbox;
  55865. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  55866. // first look for points inside the triangle in increasing z-order
  55867. var p = ear.nextZ;
  55868. while (p && p.z <= maxZ) {
  55869. if (p !== ear.prev &&
  55870. p !== ear.next &&
  55871. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  55872. area(p.prev, p, p.next) >= 0)
  55873. return false;
  55874. p = p.nextZ;
  55875. }
  55876. // then look for points in decreasing z-order
  55877. p = ear.prevZ;
  55878. while (p && p.z >= minZ) {
  55879. if (p !== ear.prev &&
  55880. p !== ear.next &&
  55881. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  55882. area(p.prev, p, p.next) >= 0)
  55883. return false;
  55884. p = p.prevZ;
  55885. }
  55886. return true;
  55887. }
  55888. // go through all polygon nodes and cure small local self-intersections
  55889. function cureLocalIntersections(start, triangles, dim) {
  55890. var p = start;
  55891. do {
  55892. var a = p.prev, b = p.next.next;
  55893. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  55894. triangles.push(a.i / dim);
  55895. triangles.push(p.i / dim);
  55896. triangles.push(b.i / dim);
  55897. // remove two nodes involved
  55898. removeNode(p);
  55899. removeNode(p.next);
  55900. p = start = b;
  55901. }
  55902. p = p.next;
  55903. } while (p !== start);
  55904. return p;
  55905. }
  55906. // try splitting polygon into two and triangulate them independently
  55907. function splitEarcut(start, triangles, dim, minX, minY, size) {
  55908. // look for a valid diagonal that divides the polygon into two
  55909. var a = start;
  55910. do {
  55911. var b = a.next.next;
  55912. while (b !== a.prev) {
  55913. if (a.i !== b.i && isValidDiagonal(a, b)) {
  55914. // split the polygon in two by the diagonal
  55915. var c = splitPolygon(a, b);
  55916. // filter colinear points around the cuts
  55917. a = filterPoints(a, a.next);
  55918. c = filterPoints(c, c.next);
  55919. // run earcut on each half
  55920. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  55921. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  55922. return;
  55923. }
  55924. b = b.next;
  55925. }
  55926. a = a.next;
  55927. } while (a !== start);
  55928. }
  55929. // link every hole into the outer loop, producing a single-ring polygon without holes
  55930. function eliminateHoles(data, holeIndices, outerNode, dim) {
  55931. var queue = [], i, len, start, end, list;
  55932. for (i = 0, len = holeIndices.length; i < len; i++) {
  55933. start = holeIndices[i] * dim;
  55934. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  55935. list = linkedList(data, start, end, dim, false);
  55936. if (list === list.next)
  55937. list.steiner = true;
  55938. queue.push(getLeftmost(list));
  55939. }
  55940. queue.sort(compareX);
  55941. // process holes from left to right
  55942. for (i = 0; i < queue.length; i++) {
  55943. eliminateHole(queue[i], outerNode);
  55944. outerNode = filterPoints(outerNode, outerNode.next);
  55945. }
  55946. return outerNode;
  55947. }
  55948. function compareX(a, b) {
  55949. return a.x - b.x;
  55950. }
  55951. // find a bridge between vertices that connects hole with an outer ring and and link it
  55952. function eliminateHole(hole, outerNode) {
  55953. outerNode = findHoleBridge(hole, outerNode);
  55954. if (outerNode) {
  55955. var b = splitPolygon(outerNode, hole);
  55956. filterPoints(b, b.next);
  55957. }
  55958. }
  55959. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  55960. function findHoleBridge(hole, outerNode) {
  55961. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  55962. // find a segment intersected by a ray from the hole's leftmost point to the left;
  55963. // segment's endpoint with lesser x will be potential connection point
  55964. do {
  55965. if (hy <= p.y && hy >= p.next.y) {
  55966. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  55967. if (x <= hx && x > qx) {
  55968. qx = x;
  55969. if (x === hx) {
  55970. if (hy === p.y)
  55971. return p;
  55972. if (hy === p.next.y)
  55973. return p.next;
  55974. }
  55975. m = p.x < p.next.x ? p : p.next;
  55976. }
  55977. }
  55978. p = p.next;
  55979. } while (p !== outerNode);
  55980. if (!m)
  55981. return null;
  55982. if (hx === qx)
  55983. return m.prev; // hole touches outer segment; pick lower endpoint
  55984. // look for points inside the triangle of hole point, segment intersection and endpoint;
  55985. // if there are no points found, we have a valid connection;
  55986. // otherwise choose the point of the minimum angle with the ray as connection point
  55987. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  55988. p = m.next;
  55989. while (p !== stop) {
  55990. if (hx >= p.x &&
  55991. p.x >= mx &&
  55992. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  55993. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  55994. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  55995. m = p;
  55996. tanMin = tan;
  55997. }
  55998. }
  55999. p = p.next;
  56000. }
  56001. return m;
  56002. }
  56003. // interlink polygon nodes in z-order
  56004. function indexCurve(start, minX, minY, size) {
  56005. var p = start;
  56006. do {
  56007. if (p.z === null)
  56008. p.z = zOrder(p.x, p.y, minX, minY, size);
  56009. p.prevZ = p.prev;
  56010. p.nextZ = p.next;
  56011. p = p.next;
  56012. } while (p !== start);
  56013. p.prevZ.nextZ = null;
  56014. p.prevZ = null;
  56015. sortLinked(p);
  56016. }
  56017. // Simon Tatham's linked list merge sort algorithm
  56018. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  56019. function sortLinked(list) {
  56020. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  56021. do {
  56022. p = list;
  56023. list = null;
  56024. tail = null;
  56025. numMerges = 0;
  56026. while (p) {
  56027. numMerges++;
  56028. q = p;
  56029. pSize = 0;
  56030. for (i = 0; i < inSize; i++) {
  56031. pSize++;
  56032. q = q.nextZ;
  56033. if (!q)
  56034. break;
  56035. }
  56036. qSize = inSize;
  56037. while (pSize > 0 || (qSize > 0 && q)) {
  56038. if (pSize === 0) {
  56039. e = q;
  56040. q = q.nextZ;
  56041. qSize--;
  56042. }
  56043. else if (qSize === 0 || !q) {
  56044. e = p;
  56045. p = p.nextZ;
  56046. pSize--;
  56047. }
  56048. else if (p.z <= q.z) {
  56049. e = p;
  56050. p = p.nextZ;
  56051. pSize--;
  56052. }
  56053. else {
  56054. e = q;
  56055. q = q.nextZ;
  56056. qSize--;
  56057. }
  56058. if (tail)
  56059. tail.nextZ = e;
  56060. else
  56061. list = e;
  56062. e.prevZ = tail;
  56063. tail = e;
  56064. }
  56065. p = q;
  56066. }
  56067. tail.nextZ = null;
  56068. inSize *= 2;
  56069. } while (numMerges > 1);
  56070. return list;
  56071. }
  56072. // z-order of a point given coords and size of the data bounding box
  56073. function zOrder(x, y, minX, minY, size) {
  56074. // coords are transformed into non-negative 15-bit integer range
  56075. x = 32767 * (x - minX) / size;
  56076. y = 32767 * (y - minY) / size;
  56077. x = (x | (x << 8)) & 0x00FF00FF;
  56078. x = (x | (x << 4)) & 0x0F0F0F0F;
  56079. x = (x | (x << 2)) & 0x33333333;
  56080. x = (x | (x << 1)) & 0x55555555;
  56081. y = (y | (y << 8)) & 0x00FF00FF;
  56082. y = (y | (y << 4)) & 0x0F0F0F0F;
  56083. y = (y | (y << 2)) & 0x33333333;
  56084. y = (y | (y << 1)) & 0x55555555;
  56085. return x | (y << 1);
  56086. }
  56087. // find the leftmost node of a polygon ring
  56088. function getLeftmost(start) {
  56089. var p = start, leftmost = start;
  56090. do {
  56091. if (p.x < leftmost.x)
  56092. leftmost = p;
  56093. p = p.next;
  56094. } while (p !== start);
  56095. return leftmost;
  56096. }
  56097. // check if a point lies within a convex triangle
  56098. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  56099. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  56100. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  56101. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  56102. }
  56103. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  56104. function isValidDiagonal(a, b) {
  56105. return a.next.i !== b.i &&
  56106. a.prev.i !== b.i &&
  56107. !intersectsPolygon(a, b) &&
  56108. locallyInside(a, b) &&
  56109. locallyInside(b, a) &&
  56110. middleInside(a, b);
  56111. }
  56112. // signed area of a triangle
  56113. function area(p, q, r) {
  56114. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  56115. }
  56116. // check if two points are equal
  56117. function equals(p1, p2) {
  56118. return p1.x === p2.x && p1.y === p2.y;
  56119. }
  56120. // check if two segments intersect
  56121. function intersects(p1, q1, p2, q2) {
  56122. if ((equals(p1, q1) && equals(p2, q2)) ||
  56123. (equals(p1, q2) && equals(p2, q1)))
  56124. return true;
  56125. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  56126. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  56127. }
  56128. // check if a polygon diagonal intersects any polygon segments
  56129. function intersectsPolygon(a, b) {
  56130. var p = a;
  56131. do {
  56132. if (p.i !== a.i &&
  56133. p.next.i !== a.i &&
  56134. p.i !== b.i &&
  56135. p.next.i !== b.i &&
  56136. intersects(p, p.next, a, b))
  56137. return true;
  56138. p = p.next;
  56139. } while (p !== a);
  56140. return false;
  56141. }
  56142. // check if a polygon diagonal is locally inside the polygon
  56143. function locallyInside(a, b) {
  56144. return area(a.prev, a, a.next) < 0
  56145. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  56146. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  56147. }
  56148. // check if the middle point of a polygon diagonal is inside the polygon
  56149. function middleInside(a, b) {
  56150. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  56151. do {
  56152. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  56153. inside = !inside;
  56154. p = p.next;
  56155. } while (p !== a);
  56156. return inside;
  56157. }
  56158. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  56159. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  56160. function splitPolygon(a, b) {
  56161. 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;
  56162. a.next = b;
  56163. b.prev = a;
  56164. a2.next = an;
  56165. an.prev = a2;
  56166. b2.next = a2;
  56167. a2.prev = b2;
  56168. bp.next = b2;
  56169. b2.prev = bp;
  56170. return b2;
  56171. }
  56172. // create a node and optionally link it with previous one (in a circular doubly linked list)
  56173. function insertNode(i, x, y, last) {
  56174. var p = new Node(i, x, y);
  56175. if (!last) {
  56176. p.prev = p;
  56177. p.next = p;
  56178. }
  56179. else {
  56180. p.next = last.next;
  56181. p.prev = last;
  56182. last.next.prev = p;
  56183. last.next = p;
  56184. }
  56185. return p;
  56186. }
  56187. function removeNode(p) {
  56188. p.next.prev = p.prev;
  56189. p.prev.next = p.next;
  56190. if (p.prevZ)
  56191. p.prevZ.nextZ = p.nextZ;
  56192. if (p.nextZ)
  56193. p.nextZ.prevZ = p.prevZ;
  56194. }
  56195. function Node(i, x, y) {
  56196. // vertice index in coordinates array
  56197. this.i = i;
  56198. // vertex coordinates
  56199. this.x = x;
  56200. this.y = y;
  56201. // previous and next vertice nodes in a polygon ring
  56202. this.prev = null;
  56203. this.next = null;
  56204. // z-order curve value
  56205. this.z = null;
  56206. // previous and next nodes in z-order
  56207. this.prevZ = null;
  56208. this.nextZ = null;
  56209. // indicates whether this is a steiner point
  56210. this.steiner = false;
  56211. }
  56212. /**
  56213. * return a percentage difference between the polygon area and its triangulation area;
  56214. * used to verify correctness of triangulation
  56215. */
  56216. function deviation(data, holeIndices, dim, triangles) {
  56217. var hasHoles = holeIndices && holeIndices.length;
  56218. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  56219. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  56220. if (hasHoles) {
  56221. for (var i = 0, len = holeIndices.length; i < len; i++) {
  56222. var start = holeIndices[i] * dim;
  56223. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  56224. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  56225. }
  56226. }
  56227. var trianglesArea = 0;
  56228. for (i = 0; i < triangles.length; i += 3) {
  56229. var a = triangles[i] * dim;
  56230. var b = triangles[i + 1] * dim;
  56231. var c = triangles[i + 2] * dim;
  56232. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  56233. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  56234. }
  56235. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  56236. }
  56237. Earcut.deviation = deviation;
  56238. ;
  56239. function signedArea(data, start, end, dim) {
  56240. var sum = 0;
  56241. for (var i = start, j = end - dim; i < end; i += dim) {
  56242. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  56243. j = i;
  56244. }
  56245. return sum;
  56246. }
  56247. /**
  56248. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  56249. */
  56250. function flatten(data) {
  56251. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  56252. for (var i = 0; i < data.length; i++) {
  56253. for (var j = 0; j < data[i].length; j++) {
  56254. for (var d = 0; d < dim; d++)
  56255. result.vertices.push(data[i][j][d]);
  56256. }
  56257. if (i > 0) {
  56258. holeIndex += data[i - 1].length;
  56259. result.holes.push(holeIndex);
  56260. }
  56261. }
  56262. return result;
  56263. }
  56264. Earcut.flatten = flatten;
  56265. ;
  56266. })(Earcut || (Earcut = {}));
  56267. //# sourceMappingURL=babylon.earcut.js.map
  56268. /// <reference path="..\Math\babylon.math.ts" />
  56269. var BABYLON;
  56270. (function (BABYLON) {
  56271. var IndexedVector2 = (function (_super) {
  56272. __extends(IndexedVector2, _super);
  56273. function IndexedVector2(original, index) {
  56274. var _this = _super.call(this, original.x, original.y) || this;
  56275. _this.index = index;
  56276. return _this;
  56277. }
  56278. return IndexedVector2;
  56279. }(BABYLON.Vector2));
  56280. var PolygonPoints = (function () {
  56281. function PolygonPoints() {
  56282. this.elements = new Array();
  56283. }
  56284. PolygonPoints.prototype.add = function (originalPoints) {
  56285. var _this = this;
  56286. var result = new Array();
  56287. originalPoints.forEach(function (point) {
  56288. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  56289. var newPoint = new IndexedVector2(point, _this.elements.length);
  56290. result.push(newPoint);
  56291. _this.elements.push(newPoint);
  56292. }
  56293. });
  56294. return result;
  56295. };
  56296. PolygonPoints.prototype.computeBounds = function () {
  56297. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  56298. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  56299. this.elements.forEach(function (point) {
  56300. // x
  56301. if (point.x < lmin.x) {
  56302. lmin.x = point.x;
  56303. }
  56304. else if (point.x > lmax.x) {
  56305. lmax.x = point.x;
  56306. }
  56307. // y
  56308. if (point.y < lmin.y) {
  56309. lmin.y = point.y;
  56310. }
  56311. else if (point.y > lmax.y) {
  56312. lmax.y = point.y;
  56313. }
  56314. });
  56315. return {
  56316. min: lmin,
  56317. max: lmax,
  56318. width: lmax.x - lmin.x,
  56319. height: lmax.y - lmin.y
  56320. };
  56321. };
  56322. return PolygonPoints;
  56323. }());
  56324. var Polygon = (function () {
  56325. function Polygon() {
  56326. }
  56327. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  56328. return [
  56329. new BABYLON.Vector2(xmin, ymin),
  56330. new BABYLON.Vector2(xmax, ymin),
  56331. new BABYLON.Vector2(xmax, ymax),
  56332. new BABYLON.Vector2(xmin, ymax)
  56333. ];
  56334. };
  56335. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  56336. if (cx === void 0) { cx = 0; }
  56337. if (cy === void 0) { cy = 0; }
  56338. if (numberOfSides === void 0) { numberOfSides = 32; }
  56339. var result = new Array();
  56340. var angle = 0;
  56341. var increment = (Math.PI * 2) / numberOfSides;
  56342. for (var i = 0; i < numberOfSides; i++) {
  56343. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  56344. angle -= increment;
  56345. }
  56346. return result;
  56347. };
  56348. Polygon.Parse = function (input) {
  56349. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  56350. var i, result = [];
  56351. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  56352. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  56353. }
  56354. return result;
  56355. };
  56356. Polygon.StartingAt = function (x, y) {
  56357. return BABYLON.Path2.StartingAt(x, y);
  56358. };
  56359. return Polygon;
  56360. }());
  56361. BABYLON.Polygon = Polygon;
  56362. var PolygonMeshBuilder = (function () {
  56363. function PolygonMeshBuilder(name, contours, scene) {
  56364. this._points = new PolygonPoints();
  56365. this._outlinepoints = new PolygonPoints();
  56366. this._holes = [];
  56367. this._epoints = new Array();
  56368. this._eholes = new Array();
  56369. this._name = name;
  56370. this._scene = scene;
  56371. var points;
  56372. if (contours instanceof BABYLON.Path2) {
  56373. points = contours.getPoints();
  56374. }
  56375. else {
  56376. points = contours;
  56377. }
  56378. this._addToepoint(points);
  56379. this._points.add(points);
  56380. this._outlinepoints.add(points);
  56381. }
  56382. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  56383. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  56384. var p = points_1[_i];
  56385. this._epoints.push(p.x, p.y);
  56386. }
  56387. };
  56388. PolygonMeshBuilder.prototype.addHole = function (hole) {
  56389. this._points.add(hole);
  56390. var holepoints = new PolygonPoints();
  56391. holepoints.add(hole);
  56392. this._holes.push(holepoints);
  56393. this._eholes.push(this._epoints.length / 2);
  56394. this._addToepoint(hole);
  56395. return this;
  56396. };
  56397. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  56398. var _this = this;
  56399. if (updatable === void 0) { updatable = false; }
  56400. var result = new BABYLON.Mesh(this._name, this._scene);
  56401. var normals = [];
  56402. var positions = [];
  56403. var uvs = [];
  56404. var bounds = this._points.computeBounds();
  56405. this._points.elements.forEach(function (p) {
  56406. normals.push(0, 1.0, 0);
  56407. positions.push(p.x, 0, p.y);
  56408. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  56409. });
  56410. var indices = [];
  56411. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  56412. for (var i = 0; i < res.length; i++) {
  56413. indices.push(res[i]);
  56414. }
  56415. if (depth > 0) {
  56416. var positionscount = (positions.length / 3); //get the current pointcount
  56417. this._points.elements.forEach(function (p) {
  56418. normals.push(0, -1.0, 0);
  56419. positions.push(p.x, -depth, p.y);
  56420. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  56421. });
  56422. var totalCount = indices.length;
  56423. for (var i = 0; i < totalCount; i += 3) {
  56424. var i0 = indices[i + 0];
  56425. var i1 = indices[i + 1];
  56426. var i2 = indices[i + 2];
  56427. indices.push(i2 + positionscount);
  56428. indices.push(i1 + positionscount);
  56429. indices.push(i0 + positionscount);
  56430. }
  56431. //Add the sides
  56432. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  56433. this._holes.forEach(function (hole) {
  56434. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  56435. });
  56436. }
  56437. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  56438. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  56439. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  56440. result.setIndices(indices);
  56441. return result;
  56442. };
  56443. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  56444. var StartIndex = positions.length / 3;
  56445. var ulength = 0;
  56446. for (var i = 0; i < points.elements.length; i++) {
  56447. var p = points.elements[i];
  56448. var p1;
  56449. if ((i + 1) > points.elements.length - 1) {
  56450. p1 = points.elements[0];
  56451. }
  56452. else {
  56453. p1 = points.elements[i + 1];
  56454. }
  56455. positions.push(p.x, 0, p.y);
  56456. positions.push(p.x, -depth, p.y);
  56457. positions.push(p1.x, 0, p1.y);
  56458. positions.push(p1.x, -depth, p1.y);
  56459. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  56460. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  56461. var v3 = v2.subtract(v1);
  56462. var v4 = new BABYLON.Vector3(0, 1, 0);
  56463. var vn = BABYLON.Vector3.Cross(v3, v4);
  56464. vn = vn.normalize();
  56465. uvs.push(ulength / bounds.width, 0);
  56466. uvs.push(ulength / bounds.width, 1);
  56467. ulength += v3.length();
  56468. uvs.push((ulength / bounds.width), 0);
  56469. uvs.push((ulength / bounds.width), 1);
  56470. if (!flip) {
  56471. normals.push(-vn.x, -vn.y, -vn.z);
  56472. normals.push(-vn.x, -vn.y, -vn.z);
  56473. normals.push(-vn.x, -vn.y, -vn.z);
  56474. normals.push(-vn.x, -vn.y, -vn.z);
  56475. indices.push(StartIndex);
  56476. indices.push(StartIndex + 1);
  56477. indices.push(StartIndex + 2);
  56478. indices.push(StartIndex + 1);
  56479. indices.push(StartIndex + 3);
  56480. indices.push(StartIndex + 2);
  56481. }
  56482. else {
  56483. normals.push(vn.x, vn.y, vn.z);
  56484. normals.push(vn.x, vn.y, vn.z);
  56485. normals.push(vn.x, vn.y, vn.z);
  56486. normals.push(vn.x, vn.y, vn.z);
  56487. indices.push(StartIndex);
  56488. indices.push(StartIndex + 2);
  56489. indices.push(StartIndex + 1);
  56490. indices.push(StartIndex + 1);
  56491. indices.push(StartIndex + 2);
  56492. indices.push(StartIndex + 3);
  56493. }
  56494. StartIndex += 4;
  56495. }
  56496. ;
  56497. };
  56498. return PolygonMeshBuilder;
  56499. }());
  56500. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  56501. })(BABYLON || (BABYLON = {}));
  56502. //# sourceMappingURL=babylon.polygonMesh.js.map
  56503. var BABYLON;
  56504. (function (BABYLON) {
  56505. // Unique ID when we import meshes from Babylon to CSG
  56506. var currentCSGMeshId = 0;
  56507. // # class Vertex
  56508. // Represents a vertex of a polygon. Use your own vertex class instead of this
  56509. // one to provide additional features like texture coordinates and vertex
  56510. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  56511. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  56512. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  56513. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  56514. // is not used anywhere else.
  56515. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  56516. var Vertex = (function () {
  56517. function Vertex(pos, normal, uv) {
  56518. this.pos = pos;
  56519. this.normal = normal;
  56520. this.uv = uv;
  56521. }
  56522. Vertex.prototype.clone = function () {
  56523. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  56524. };
  56525. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  56526. // orientation of a polygon is flipped.
  56527. Vertex.prototype.flip = function () {
  56528. this.normal = this.normal.scale(-1);
  56529. };
  56530. // Create a new vertex between this vertex and `other` by linearly
  56531. // interpolating all properties using a parameter of `t`. Subclasses should
  56532. // override this to interpolate additional properties.
  56533. Vertex.prototype.interpolate = function (other, t) {
  56534. 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));
  56535. };
  56536. return Vertex;
  56537. }());
  56538. // # class Plane
  56539. // Represents a plane in 3D space.
  56540. var Plane = (function () {
  56541. function Plane(normal, w) {
  56542. this.normal = normal;
  56543. this.w = w;
  56544. }
  56545. Plane.FromPoints = function (a, b, c) {
  56546. var v0 = c.subtract(a);
  56547. var v1 = b.subtract(a);
  56548. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  56549. return null;
  56550. }
  56551. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  56552. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  56553. };
  56554. Plane.prototype.clone = function () {
  56555. return new Plane(this.normal.clone(), this.w);
  56556. };
  56557. Plane.prototype.flip = function () {
  56558. this.normal.scaleInPlace(-1);
  56559. this.w = -this.w;
  56560. };
  56561. // Split `polygon` by this plane if needed, then put the polygon or polygon
  56562. // fragments in the appropriate lists. Coplanar polygons go into either
  56563. // `coplanarFront` or `coplanarBack` depending on their orientation with
  56564. // respect to this plane. Polygons in front or in back of this plane go into
  56565. // either `front` or `back`.
  56566. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  56567. var COPLANAR = 0;
  56568. var FRONT = 1;
  56569. var BACK = 2;
  56570. var SPANNING = 3;
  56571. // Classify each point as well as the entire polygon into one of the above
  56572. // four classes.
  56573. var polygonType = 0;
  56574. var types = [];
  56575. var i;
  56576. var t;
  56577. for (i = 0; i < polygon.vertices.length; i++) {
  56578. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  56579. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  56580. polygonType |= type;
  56581. types.push(type);
  56582. }
  56583. // Put the polygon in the correct list, splitting it when necessary.
  56584. switch (polygonType) {
  56585. case COPLANAR:
  56586. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  56587. break;
  56588. case FRONT:
  56589. front.push(polygon);
  56590. break;
  56591. case BACK:
  56592. back.push(polygon);
  56593. break;
  56594. case SPANNING:
  56595. var f = [], b = [];
  56596. for (i = 0; i < polygon.vertices.length; i++) {
  56597. var j = (i + 1) % polygon.vertices.length;
  56598. var ti = types[i], tj = types[j];
  56599. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  56600. if (ti !== BACK)
  56601. f.push(vi);
  56602. if (ti !== FRONT)
  56603. b.push(ti !== BACK ? vi.clone() : vi);
  56604. if ((ti | tj) === SPANNING) {
  56605. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  56606. var v = vi.interpolate(vj, t);
  56607. f.push(v);
  56608. b.push(v.clone());
  56609. }
  56610. }
  56611. var poly;
  56612. if (f.length >= 3) {
  56613. poly = new Polygon(f, polygon.shared);
  56614. if (poly.plane)
  56615. front.push(poly);
  56616. }
  56617. if (b.length >= 3) {
  56618. poly = new Polygon(b, polygon.shared);
  56619. if (poly.plane)
  56620. back.push(poly);
  56621. }
  56622. break;
  56623. }
  56624. };
  56625. return Plane;
  56626. }());
  56627. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  56628. // point is on the plane.
  56629. Plane.EPSILON = 1e-5;
  56630. // # class Polygon
  56631. // Represents a convex polygon. The vertices used to initialize a polygon must
  56632. // be coplanar and form a convex loop.
  56633. //
  56634. // Each convex polygon has a `shared` property, which is shared between all
  56635. // polygons that are clones of each other or were split from the same polygon.
  56636. // This can be used to define per-polygon properties (such as surface color).
  56637. var Polygon = (function () {
  56638. function Polygon(vertices, shared) {
  56639. this.vertices = vertices;
  56640. this.shared = shared;
  56641. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  56642. }
  56643. Polygon.prototype.clone = function () {
  56644. var vertices = this.vertices.map(function (v) { return v.clone(); });
  56645. return new Polygon(vertices, this.shared);
  56646. };
  56647. Polygon.prototype.flip = function () {
  56648. this.vertices.reverse().map(function (v) { v.flip(); });
  56649. this.plane.flip();
  56650. };
  56651. return Polygon;
  56652. }());
  56653. // # class Node
  56654. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  56655. // by picking a polygon to split along. That polygon (and all other coplanar
  56656. // polygons) are added directly to that node and the other polygons are added to
  56657. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  56658. // no distinction between internal and leaf nodes.
  56659. var Node = (function () {
  56660. function Node(polygons) {
  56661. this.plane = null;
  56662. this.front = null;
  56663. this.back = null;
  56664. this.polygons = [];
  56665. if (polygons) {
  56666. this.build(polygons);
  56667. }
  56668. }
  56669. Node.prototype.clone = function () {
  56670. var node = new Node();
  56671. node.plane = this.plane && this.plane.clone();
  56672. node.front = this.front && this.front.clone();
  56673. node.back = this.back && this.back.clone();
  56674. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  56675. return node;
  56676. };
  56677. // Convert solid space to empty space and empty space to solid space.
  56678. Node.prototype.invert = function () {
  56679. for (var i = 0; i < this.polygons.length; i++) {
  56680. this.polygons[i].flip();
  56681. }
  56682. if (this.plane) {
  56683. this.plane.flip();
  56684. }
  56685. if (this.front) {
  56686. this.front.invert();
  56687. }
  56688. if (this.back) {
  56689. this.back.invert();
  56690. }
  56691. var temp = this.front;
  56692. this.front = this.back;
  56693. this.back = temp;
  56694. };
  56695. // Recursively remove all polygons in `polygons` that are inside this BSP
  56696. // tree.
  56697. Node.prototype.clipPolygons = function (polygons) {
  56698. if (!this.plane)
  56699. return polygons.slice();
  56700. var front = [], back = [];
  56701. for (var i = 0; i < polygons.length; i++) {
  56702. this.plane.splitPolygon(polygons[i], front, back, front, back);
  56703. }
  56704. if (this.front) {
  56705. front = this.front.clipPolygons(front);
  56706. }
  56707. if (this.back) {
  56708. back = this.back.clipPolygons(back);
  56709. }
  56710. else {
  56711. back = [];
  56712. }
  56713. return front.concat(back);
  56714. };
  56715. // Remove all polygons in this BSP tree that are inside the other BSP tree
  56716. // `bsp`.
  56717. Node.prototype.clipTo = function (bsp) {
  56718. this.polygons = bsp.clipPolygons(this.polygons);
  56719. if (this.front)
  56720. this.front.clipTo(bsp);
  56721. if (this.back)
  56722. this.back.clipTo(bsp);
  56723. };
  56724. // Return a list of all polygons in this BSP tree.
  56725. Node.prototype.allPolygons = function () {
  56726. var polygons = this.polygons.slice();
  56727. if (this.front)
  56728. polygons = polygons.concat(this.front.allPolygons());
  56729. if (this.back)
  56730. polygons = polygons.concat(this.back.allPolygons());
  56731. return polygons;
  56732. };
  56733. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  56734. // new polygons are filtered down to the bottom of the tree and become new
  56735. // nodes there. Each set of polygons is partitioned using the first polygon
  56736. // (no heuristic is used to pick a good split).
  56737. Node.prototype.build = function (polygons) {
  56738. if (!polygons.length)
  56739. return;
  56740. if (!this.plane)
  56741. this.plane = polygons[0].plane.clone();
  56742. var front = [], back = [];
  56743. for (var i = 0; i < polygons.length; i++) {
  56744. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  56745. }
  56746. if (front.length) {
  56747. if (!this.front)
  56748. this.front = new Node();
  56749. this.front.build(front);
  56750. }
  56751. if (back.length) {
  56752. if (!this.back)
  56753. this.back = new Node();
  56754. this.back.build(back);
  56755. }
  56756. };
  56757. return Node;
  56758. }());
  56759. var CSG = (function () {
  56760. function CSG() {
  56761. this.polygons = new Array();
  56762. }
  56763. // Convert BABYLON.Mesh to BABYLON.CSG
  56764. CSG.FromMesh = function (mesh) {
  56765. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  56766. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  56767. if (mesh instanceof BABYLON.Mesh) {
  56768. mesh.computeWorldMatrix(true);
  56769. matrix = mesh.getWorldMatrix();
  56770. meshPosition = mesh.position.clone();
  56771. meshRotation = mesh.rotation.clone();
  56772. if (mesh.rotationQuaternion) {
  56773. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  56774. }
  56775. meshScaling = mesh.scaling.clone();
  56776. }
  56777. else {
  56778. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  56779. }
  56780. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56781. var subMeshes = mesh.subMeshes;
  56782. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  56783. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  56784. vertices = [];
  56785. for (var j = 0; j < 3; j++) {
  56786. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  56787. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  56788. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  56789. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  56790. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  56791. vertex = new Vertex(position, normal, uv);
  56792. vertices.push(vertex);
  56793. }
  56794. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  56795. // To handle the case of degenerated triangle
  56796. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  56797. if (polygon.plane)
  56798. polygons.push(polygon);
  56799. }
  56800. }
  56801. var csg = CSG.FromPolygons(polygons);
  56802. csg.matrix = matrix;
  56803. csg.position = meshPosition;
  56804. csg.rotation = meshRotation;
  56805. csg.scaling = meshScaling;
  56806. csg.rotationQuaternion = meshRotationQuaternion;
  56807. currentCSGMeshId++;
  56808. return csg;
  56809. };
  56810. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  56811. CSG.FromPolygons = function (polygons) {
  56812. var csg = new CSG();
  56813. csg.polygons = polygons;
  56814. return csg;
  56815. };
  56816. CSG.prototype.clone = function () {
  56817. var csg = new CSG();
  56818. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  56819. csg.copyTransformAttributes(this);
  56820. return csg;
  56821. };
  56822. CSG.prototype.toPolygons = function () {
  56823. return this.polygons;
  56824. };
  56825. CSG.prototype.union = function (csg) {
  56826. var a = new Node(this.clone().polygons);
  56827. var b = new Node(csg.clone().polygons);
  56828. a.clipTo(b);
  56829. b.clipTo(a);
  56830. b.invert();
  56831. b.clipTo(a);
  56832. b.invert();
  56833. a.build(b.allPolygons());
  56834. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  56835. };
  56836. CSG.prototype.unionInPlace = function (csg) {
  56837. var a = new Node(this.polygons);
  56838. var b = new Node(csg.polygons);
  56839. a.clipTo(b);
  56840. b.clipTo(a);
  56841. b.invert();
  56842. b.clipTo(a);
  56843. b.invert();
  56844. a.build(b.allPolygons());
  56845. this.polygons = a.allPolygons();
  56846. };
  56847. CSG.prototype.subtract = function (csg) {
  56848. var a = new Node(this.clone().polygons);
  56849. var b = new Node(csg.clone().polygons);
  56850. a.invert();
  56851. a.clipTo(b);
  56852. b.clipTo(a);
  56853. b.invert();
  56854. b.clipTo(a);
  56855. b.invert();
  56856. a.build(b.allPolygons());
  56857. a.invert();
  56858. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  56859. };
  56860. CSG.prototype.subtractInPlace = function (csg) {
  56861. var a = new Node(this.polygons);
  56862. var b = new Node(csg.polygons);
  56863. a.invert();
  56864. a.clipTo(b);
  56865. b.clipTo(a);
  56866. b.invert();
  56867. b.clipTo(a);
  56868. b.invert();
  56869. a.build(b.allPolygons());
  56870. a.invert();
  56871. this.polygons = a.allPolygons();
  56872. };
  56873. CSG.prototype.intersect = function (csg) {
  56874. var a = new Node(this.clone().polygons);
  56875. var b = new Node(csg.clone().polygons);
  56876. a.invert();
  56877. b.clipTo(a);
  56878. b.invert();
  56879. a.clipTo(b);
  56880. b.clipTo(a);
  56881. a.build(b.allPolygons());
  56882. a.invert();
  56883. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  56884. };
  56885. CSG.prototype.intersectInPlace = function (csg) {
  56886. var a = new Node(this.polygons);
  56887. var b = new Node(csg.polygons);
  56888. a.invert();
  56889. b.clipTo(a);
  56890. b.invert();
  56891. a.clipTo(b);
  56892. b.clipTo(a);
  56893. a.build(b.allPolygons());
  56894. a.invert();
  56895. this.polygons = a.allPolygons();
  56896. };
  56897. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  56898. // not modified.
  56899. CSG.prototype.inverse = function () {
  56900. var csg = this.clone();
  56901. csg.inverseInPlace();
  56902. return csg;
  56903. };
  56904. CSG.prototype.inverseInPlace = function () {
  56905. this.polygons.map(function (p) { p.flip(); });
  56906. };
  56907. // This is used to keep meshes transformations so they can be restored
  56908. // when we build back a Babylon Mesh
  56909. // NB : All CSG operations are performed in world coordinates
  56910. CSG.prototype.copyTransformAttributes = function (csg) {
  56911. this.matrix = csg.matrix;
  56912. this.position = csg.position;
  56913. this.rotation = csg.rotation;
  56914. this.scaling = csg.scaling;
  56915. this.rotationQuaternion = csg.rotationQuaternion;
  56916. return this;
  56917. };
  56918. // Build Raw mesh from CSG
  56919. // Coordinates here are in world space
  56920. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  56921. var matrix = this.matrix.clone();
  56922. matrix.invert();
  56923. 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;
  56924. if (keepSubMeshes) {
  56925. // Sort Polygons, since subMeshes are indices range
  56926. polygons.sort(function (a, b) {
  56927. if (a.shared.meshId === b.shared.meshId) {
  56928. return a.shared.subMeshId - b.shared.subMeshId;
  56929. }
  56930. else {
  56931. return a.shared.meshId - b.shared.meshId;
  56932. }
  56933. });
  56934. }
  56935. for (var i = 0, il = polygons.length; i < il; i++) {
  56936. polygon = polygons[i];
  56937. // Building SubMeshes
  56938. if (!subMesh_dict[polygon.shared.meshId]) {
  56939. subMesh_dict[polygon.shared.meshId] = {};
  56940. }
  56941. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  56942. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  56943. indexStart: +Infinity,
  56944. indexEnd: -Infinity,
  56945. materialIndex: polygon.shared.materialIndex
  56946. };
  56947. }
  56948. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  56949. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  56950. polygonIndices[0] = 0;
  56951. polygonIndices[1] = j - 1;
  56952. polygonIndices[2] = j;
  56953. for (var k = 0; k < 3; k++) {
  56954. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  56955. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  56956. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  56957. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  56958. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  56959. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  56960. // Check if 2 points can be merged
  56961. if (!(typeof vertex_idx !== 'undefined' &&
  56962. normals[vertex_idx * 3] === localNormal.x &&
  56963. normals[vertex_idx * 3 + 1] === localNormal.y &&
  56964. normals[vertex_idx * 3 + 2] === localNormal.z &&
  56965. uvs[vertex_idx * 2] === uv.x &&
  56966. uvs[vertex_idx * 2 + 1] === uv.y)) {
  56967. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  56968. uvs.push(uv.x, uv.y);
  56969. normals.push(normal.x, normal.y, normal.z);
  56970. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  56971. }
  56972. indices.push(vertex_idx);
  56973. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  56974. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  56975. currentIndex++;
  56976. }
  56977. }
  56978. }
  56979. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  56980. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  56981. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  56982. mesh.setIndices(indices);
  56983. if (keepSubMeshes) {
  56984. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  56985. var materialIndexOffset = 0, materialMaxIndex;
  56986. mesh.subMeshes = new Array();
  56987. for (var m in subMesh_dict) {
  56988. materialMaxIndex = -1;
  56989. for (var sm in subMesh_dict[m]) {
  56990. subMesh_obj = subMesh_dict[m][sm];
  56991. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  56992. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  56993. }
  56994. materialIndexOffset += ++materialMaxIndex;
  56995. }
  56996. }
  56997. return mesh;
  56998. };
  56999. // Build Mesh from CSG taking material and transforms into account
  57000. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  57001. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  57002. mesh.material = material;
  57003. mesh.position.copyFrom(this.position);
  57004. mesh.rotation.copyFrom(this.rotation);
  57005. if (this.rotationQuaternion) {
  57006. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  57007. }
  57008. mesh.scaling.copyFrom(this.scaling);
  57009. mesh.computeWorldMatrix(true);
  57010. return mesh;
  57011. };
  57012. return CSG;
  57013. }());
  57014. BABYLON.CSG = CSG;
  57015. })(BABYLON || (BABYLON = {}));
  57016. //# sourceMappingURL=babylon.csg.js.map
  57017. var BABYLON;
  57018. (function (BABYLON) {
  57019. var LensFlare = (function () {
  57020. function LensFlare(size, position, color, imgUrl, system) {
  57021. this.size = size;
  57022. this.position = position;
  57023. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  57024. this.dispose = function () {
  57025. if (this.texture) {
  57026. this.texture.dispose();
  57027. }
  57028. // Remove from scene
  57029. var index = this._system.lensFlares.indexOf(this);
  57030. this._system.lensFlares.splice(index, 1);
  57031. };
  57032. this.color = color || new BABYLON.Color3(1, 1, 1);
  57033. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  57034. this._system = system;
  57035. system.lensFlares.push(this);
  57036. }
  57037. return LensFlare;
  57038. }());
  57039. BABYLON.LensFlare = LensFlare;
  57040. })(BABYLON || (BABYLON = {}));
  57041. //# sourceMappingURL=babylon.lensFlare.js.map
  57042. var BABYLON;
  57043. (function (BABYLON) {
  57044. var LensFlareSystem = (function () {
  57045. function LensFlareSystem(name, emitter, scene) {
  57046. this.name = name;
  57047. this.lensFlares = new Array();
  57048. this.borderLimit = 300;
  57049. this.viewportBorder = 0;
  57050. this.layerMask = 0x0FFFFFFF;
  57051. this._vertexBuffers = {};
  57052. this._isEnabled = true;
  57053. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57054. this._emitter = emitter;
  57055. this.id = name;
  57056. scene.lensFlareSystems.push(this);
  57057. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  57058. var engine = scene.getEngine();
  57059. // VBO
  57060. var vertices = [];
  57061. vertices.push(1, 1);
  57062. vertices.push(-1, 1);
  57063. vertices.push(-1, -1);
  57064. vertices.push(1, -1);
  57065. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  57066. // Indices
  57067. var indices = [];
  57068. indices.push(0);
  57069. indices.push(1);
  57070. indices.push(2);
  57071. indices.push(0);
  57072. indices.push(2);
  57073. indices.push(3);
  57074. this._indexBuffer = engine.createIndexBuffer(indices);
  57075. // Effects
  57076. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  57077. }
  57078. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  57079. get: function () {
  57080. return this._isEnabled;
  57081. },
  57082. set: function (value) {
  57083. this._isEnabled = value;
  57084. },
  57085. enumerable: true,
  57086. configurable: true
  57087. });
  57088. LensFlareSystem.prototype.getScene = function () {
  57089. return this._scene;
  57090. };
  57091. LensFlareSystem.prototype.getEmitter = function () {
  57092. return this._emitter;
  57093. };
  57094. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  57095. this._emitter = newEmitter;
  57096. };
  57097. LensFlareSystem.prototype.getEmitterPosition = function () {
  57098. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  57099. };
  57100. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  57101. var position = this.getEmitterPosition();
  57102. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  57103. this._positionX = position.x;
  57104. this._positionY = position.y;
  57105. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  57106. if (this.viewportBorder > 0) {
  57107. globalViewport.x -= this.viewportBorder;
  57108. globalViewport.y -= this.viewportBorder;
  57109. globalViewport.width += this.viewportBorder * 2;
  57110. globalViewport.height += this.viewportBorder * 2;
  57111. position.x += this.viewportBorder;
  57112. position.y += this.viewportBorder;
  57113. this._positionX += this.viewportBorder;
  57114. this._positionY += this.viewportBorder;
  57115. }
  57116. if (position.z > 0) {
  57117. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  57118. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  57119. return true;
  57120. }
  57121. return true;
  57122. }
  57123. return false;
  57124. };
  57125. LensFlareSystem.prototype._isVisible = function () {
  57126. if (!this._isEnabled) {
  57127. return false;
  57128. }
  57129. var emitterPosition = this.getEmitterPosition();
  57130. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  57131. var distance = direction.length();
  57132. direction.normalize();
  57133. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  57134. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  57135. return !pickInfo.hit || pickInfo.distance > distance;
  57136. };
  57137. LensFlareSystem.prototype.render = function () {
  57138. if (!this._effect.isReady())
  57139. return false;
  57140. var engine = this._scene.getEngine();
  57141. var viewport = this._scene.activeCamera.viewport;
  57142. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  57143. // Position
  57144. if (!this.computeEffectivePosition(globalViewport)) {
  57145. return false;
  57146. }
  57147. // Visibility
  57148. if (!this._isVisible()) {
  57149. return false;
  57150. }
  57151. // Intensity
  57152. var awayX;
  57153. var awayY;
  57154. if (this._positionX < this.borderLimit + globalViewport.x) {
  57155. awayX = this.borderLimit + globalViewport.x - this._positionX;
  57156. }
  57157. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  57158. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  57159. }
  57160. else {
  57161. awayX = 0;
  57162. }
  57163. if (this._positionY < this.borderLimit + globalViewport.y) {
  57164. awayY = this.borderLimit + globalViewport.y - this._positionY;
  57165. }
  57166. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  57167. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  57168. }
  57169. else {
  57170. awayY = 0;
  57171. }
  57172. var away = (awayX > awayY) ? awayX : awayY;
  57173. away -= this.viewportBorder;
  57174. if (away > this.borderLimit) {
  57175. away = this.borderLimit;
  57176. }
  57177. var intensity = 1.0 - (away / this.borderLimit);
  57178. if (intensity < 0) {
  57179. return false;
  57180. }
  57181. if (intensity > 1.0) {
  57182. intensity = 1.0;
  57183. }
  57184. if (this.viewportBorder > 0) {
  57185. globalViewport.x += this.viewportBorder;
  57186. globalViewport.y += this.viewportBorder;
  57187. globalViewport.width -= this.viewportBorder * 2;
  57188. globalViewport.height -= this.viewportBorder * 2;
  57189. this._positionX -= this.viewportBorder;
  57190. this._positionY -= this.viewportBorder;
  57191. }
  57192. // Position
  57193. var centerX = globalViewport.x + globalViewport.width / 2;
  57194. var centerY = globalViewport.y + globalViewport.height / 2;
  57195. var distX = centerX - this._positionX;
  57196. var distY = centerY - this._positionY;
  57197. // Effects
  57198. engine.enableEffect(this._effect);
  57199. engine.setState(false);
  57200. engine.setDepthBuffer(false);
  57201. // VBOs
  57202. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57203. // Flares
  57204. for (var index = 0; index < this.lensFlares.length; index++) {
  57205. var flare = this.lensFlares[index];
  57206. engine.setAlphaMode(flare.alphaMode);
  57207. var x = centerX - (distX * flare.position);
  57208. var y = centerY - (distY * flare.position);
  57209. var cw = flare.size;
  57210. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  57211. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  57212. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  57213. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  57214. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  57215. // Texture
  57216. this._effect.setTexture("textureSampler", flare.texture);
  57217. // Color
  57218. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  57219. // Draw order
  57220. engine.draw(true, 0, 6);
  57221. }
  57222. engine.setDepthBuffer(true);
  57223. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57224. return true;
  57225. };
  57226. LensFlareSystem.prototype.dispose = function () {
  57227. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57228. if (vertexBuffer) {
  57229. vertexBuffer.dispose();
  57230. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  57231. }
  57232. if (this._indexBuffer) {
  57233. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57234. this._indexBuffer = null;
  57235. }
  57236. while (this.lensFlares.length) {
  57237. this.lensFlares[0].dispose();
  57238. }
  57239. // Remove from scene
  57240. var index = this._scene.lensFlareSystems.indexOf(this);
  57241. this._scene.lensFlareSystems.splice(index, 1);
  57242. };
  57243. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  57244. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  57245. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  57246. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  57247. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  57248. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  57249. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  57250. var parsedFlare = parsedLensFlareSystem.flares[index];
  57251. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  57252. }
  57253. return lensFlareSystem;
  57254. };
  57255. LensFlareSystem.prototype.serialize = function () {
  57256. var serializationObject = {};
  57257. serializationObject.id = this.id;
  57258. serializationObject.name = this.name;
  57259. serializationObject.emitterId = this.getEmitter().id;
  57260. serializationObject.borderLimit = this.borderLimit;
  57261. serializationObject.flares = [];
  57262. for (var index = 0; index < this.lensFlares.length; index++) {
  57263. var flare = this.lensFlares[index];
  57264. serializationObject.flares.push({
  57265. size: flare.size,
  57266. position: flare.position,
  57267. color: flare.color.asArray(),
  57268. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  57269. });
  57270. }
  57271. return serializationObject;
  57272. };
  57273. return LensFlareSystem;
  57274. }());
  57275. BABYLON.LensFlareSystem = LensFlareSystem;
  57276. })(BABYLON || (BABYLON = {}));
  57277. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  57278. var BABYLON;
  57279. (function (BABYLON) {
  57280. /**
  57281. * This is a holder class for the physics joint created by the physics plugin.
  57282. * It holds a set of functions to control the underlying joint.
  57283. */
  57284. var PhysicsJoint = (function () {
  57285. function PhysicsJoint(type, jointData) {
  57286. this.type = type;
  57287. this.jointData = jointData;
  57288. jointData.nativeParams = jointData.nativeParams || {};
  57289. }
  57290. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  57291. get: function () {
  57292. return this._physicsJoint;
  57293. },
  57294. set: function (newJoint) {
  57295. if (this._physicsJoint) {
  57296. //remove from the wolrd
  57297. }
  57298. this._physicsJoint = newJoint;
  57299. },
  57300. enumerable: true,
  57301. configurable: true
  57302. });
  57303. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  57304. set: function (physicsPlugin) {
  57305. this._physicsPlugin = physicsPlugin;
  57306. },
  57307. enumerable: true,
  57308. configurable: true
  57309. });
  57310. /**
  57311. * Execute a function that is physics-plugin specific.
  57312. * @param {Function} func the function that will be executed.
  57313. * It accepts two parameters: the physics world and the physics joint.
  57314. */
  57315. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  57316. func(this._physicsPlugin.world, this._physicsJoint);
  57317. };
  57318. return PhysicsJoint;
  57319. }());
  57320. //TODO check if the native joints are the same
  57321. //Joint Types
  57322. PhysicsJoint.DistanceJoint = 0;
  57323. PhysicsJoint.HingeJoint = 1;
  57324. PhysicsJoint.BallAndSocketJoint = 2;
  57325. PhysicsJoint.WheelJoint = 3;
  57326. PhysicsJoint.SliderJoint = 4;
  57327. //OIMO
  57328. PhysicsJoint.PrismaticJoint = 5;
  57329. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  57330. PhysicsJoint.UniversalJoint = 6;
  57331. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  57332. //Cannon
  57333. //Similar to a Ball-Joint. Different in params
  57334. PhysicsJoint.PointToPointJoint = 8;
  57335. //Cannon only at the moment
  57336. PhysicsJoint.SpringJoint = 9;
  57337. PhysicsJoint.LockJoint = 10;
  57338. BABYLON.PhysicsJoint = PhysicsJoint;
  57339. /**
  57340. * A class representing a physics distance joint.
  57341. */
  57342. var DistanceJoint = (function (_super) {
  57343. __extends(DistanceJoint, _super);
  57344. function DistanceJoint(jointData) {
  57345. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  57346. }
  57347. /**
  57348. * Update the predefined distance.
  57349. */
  57350. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  57351. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  57352. };
  57353. return DistanceJoint;
  57354. }(PhysicsJoint));
  57355. BABYLON.DistanceJoint = DistanceJoint;
  57356. var MotorEnabledJoint = (function (_super) {
  57357. __extends(MotorEnabledJoint, _super);
  57358. function MotorEnabledJoint(type, jointData) {
  57359. return _super.call(this, type, jointData) || this;
  57360. }
  57361. /**
  57362. * Set the motor values.
  57363. * Attention, this function is plugin specific. Engines won't react 100% the same.
  57364. * @param {number} force the force to apply
  57365. * @param {number} maxForce max force for this motor.
  57366. */
  57367. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  57368. this._physicsPlugin.setMotor(this, force, maxForce);
  57369. };
  57370. /**
  57371. * Set the motor's limits.
  57372. * Attention, this function is plugin specific. Engines won't react 100% the same.
  57373. */
  57374. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  57375. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  57376. };
  57377. return MotorEnabledJoint;
  57378. }(PhysicsJoint));
  57379. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  57380. /**
  57381. * This class represents a single hinge physics joint
  57382. */
  57383. var HingeJoint = (function (_super) {
  57384. __extends(HingeJoint, _super);
  57385. function HingeJoint(jointData) {
  57386. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  57387. }
  57388. /**
  57389. * Set the motor values.
  57390. * Attention, this function is plugin specific. Engines won't react 100% the same.
  57391. * @param {number} force the force to apply
  57392. * @param {number} maxForce max force for this motor.
  57393. */
  57394. HingeJoint.prototype.setMotor = function (force, maxForce) {
  57395. this._physicsPlugin.setMotor(this, force, maxForce);
  57396. };
  57397. /**
  57398. * Set the motor's limits.
  57399. * Attention, this function is plugin specific. Engines won't react 100% the same.
  57400. */
  57401. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  57402. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  57403. };
  57404. return HingeJoint;
  57405. }(MotorEnabledJoint));
  57406. BABYLON.HingeJoint = HingeJoint;
  57407. /**
  57408. * This class represents a dual hinge physics joint (same as wheel joint)
  57409. */
  57410. var Hinge2Joint = (function (_super) {
  57411. __extends(Hinge2Joint, _super);
  57412. function Hinge2Joint(jointData) {
  57413. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  57414. }
  57415. /**
  57416. * Set the motor values.
  57417. * Attention, this function is plugin specific. Engines won't react 100% the same.
  57418. * @param {number} force the force to apply
  57419. * @param {number} maxForce max force for this motor.
  57420. * @param {motorIndex} the motor's index, 0 or 1.
  57421. */
  57422. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  57423. if (motorIndex === void 0) { motorIndex = 0; }
  57424. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  57425. };
  57426. /**
  57427. * Set the motor limits.
  57428. * Attention, this function is plugin specific. Engines won't react 100% the same.
  57429. * @param {number} upperLimit the upper limit
  57430. * @param {number} lowerLimit lower limit
  57431. * @param {motorIndex} the motor's index, 0 or 1.
  57432. */
  57433. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  57434. if (motorIndex === void 0) { motorIndex = 0; }
  57435. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  57436. };
  57437. return Hinge2Joint;
  57438. }(MotorEnabledJoint));
  57439. BABYLON.Hinge2Joint = Hinge2Joint;
  57440. })(BABYLON || (BABYLON = {}));
  57441. //# sourceMappingURL=babylon.physicsJoint.js.map
  57442. var BABYLON;
  57443. (function (BABYLON) {
  57444. var PhysicsImpostor = (function () {
  57445. function PhysicsImpostor(object, type, _options, _scene) {
  57446. if (_options === void 0) { _options = { mass: 0 }; }
  57447. var _this = this;
  57448. this.object = object;
  57449. this.type = type;
  57450. this._options = _options;
  57451. this._scene = _scene;
  57452. this._bodyUpdateRequired = false;
  57453. this._onBeforePhysicsStepCallbacks = new Array();
  57454. this._onAfterPhysicsStepCallbacks = new Array();
  57455. this._onPhysicsCollideCallbacks = [];
  57456. this._deltaPosition = BABYLON.Vector3.Zero();
  57457. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  57458. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  57459. /**
  57460. * this function is executed by the physics engine.
  57461. */
  57462. this.beforeStep = function () {
  57463. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  57464. //conjugate deltaRotation
  57465. if (_this._deltaRotationConjugated) {
  57466. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  57467. }
  57468. else {
  57469. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  57470. }
  57471. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  57472. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  57473. func(_this);
  57474. });
  57475. };
  57476. /**
  57477. * this function is executed by the physics engine.
  57478. */
  57479. this.afterStep = function () {
  57480. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  57481. func(_this);
  57482. });
  57483. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  57484. _this.object.position.addInPlace(_this._deltaPosition);
  57485. if (_this._deltaRotation) {
  57486. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  57487. }
  57488. };
  57489. /**
  57490. * Legacy collision detection event support
  57491. */
  57492. this.onCollideEvent = null;
  57493. //event and body object due to cannon's event-based architecture.
  57494. this.onCollide = function (e) {
  57495. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  57496. return;
  57497. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  57498. if (otherImpostor) {
  57499. // Legacy collision detection event support
  57500. if (_this.onCollideEvent) {
  57501. _this.onCollideEvent(_this, otherImpostor);
  57502. }
  57503. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  57504. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  57505. }).forEach(function (obj) {
  57506. obj.callback(_this, otherImpostor);
  57507. });
  57508. }
  57509. };
  57510. //sanity check!
  57511. if (!this.object) {
  57512. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  57513. return;
  57514. }
  57515. //legacy support for old syntax.
  57516. if (!this._scene && object.getScene) {
  57517. this._scene = object.getScene();
  57518. }
  57519. this._physicsEngine = this._scene.getPhysicsEngine();
  57520. if (!this._physicsEngine) {
  57521. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  57522. }
  57523. else {
  57524. //set the object's quaternion, if not set
  57525. if (!this.object.rotationQuaternion) {
  57526. if (this.object.rotation) {
  57527. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  57528. }
  57529. else {
  57530. this.object.rotationQuaternion = new BABYLON.Quaternion();
  57531. }
  57532. }
  57533. //default options params
  57534. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  57535. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  57536. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  57537. this._joints = [];
  57538. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  57539. if (!this.object.parent) {
  57540. this._init();
  57541. }
  57542. else if (this.object.parent.physicsImpostor) {
  57543. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  57544. }
  57545. }
  57546. }
  57547. /**
  57548. * This function will completly initialize this impostor.
  57549. * It will create a new body - but only if this mesh has no parent.
  57550. * If it has, this impostor will not be used other than to define the impostor
  57551. * of the child mesh.
  57552. */
  57553. PhysicsImpostor.prototype._init = function () {
  57554. this._physicsEngine.removeImpostor(this);
  57555. this.physicsBody = null;
  57556. this._parent = this._parent || this._getPhysicsParent();
  57557. if (!this.parent) {
  57558. this._physicsEngine.addImpostor(this);
  57559. }
  57560. };
  57561. PhysicsImpostor.prototype._getPhysicsParent = function () {
  57562. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  57563. var parentMesh = this.object.parent;
  57564. return parentMesh.physicsImpostor;
  57565. }
  57566. return;
  57567. };
  57568. /**
  57569. * Should a new body be generated.
  57570. */
  57571. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  57572. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  57573. };
  57574. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  57575. this.forceUpdate();
  57576. };
  57577. /**
  57578. * Force a regeneration of this or the parent's impostor's body.
  57579. * Use under cautious - This will remove all joints already implemented.
  57580. */
  57581. PhysicsImpostor.prototype.forceUpdate = function () {
  57582. this._init();
  57583. if (this.parent) {
  57584. this.parent.forceUpdate();
  57585. }
  57586. };
  57587. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  57588. /*public get mesh(): AbstractMesh {
  57589. return this._mesh;
  57590. }*/
  57591. /**
  57592. * Gets the body that holds this impostor. Either its own, or its parent.
  57593. */
  57594. get: function () {
  57595. return this._parent ? this._parent.physicsBody : this._physicsBody;
  57596. },
  57597. /**
  57598. * Set the physics body. Used mainly by the physics engine/plugin
  57599. */
  57600. set: function (physicsBody) {
  57601. if (this._physicsBody) {
  57602. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  57603. }
  57604. this._physicsBody = physicsBody;
  57605. this.resetUpdateFlags();
  57606. },
  57607. enumerable: true,
  57608. configurable: true
  57609. });
  57610. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  57611. get: function () {
  57612. return this._parent;
  57613. },
  57614. set: function (value) {
  57615. this._parent = value;
  57616. },
  57617. enumerable: true,
  57618. configurable: true
  57619. });
  57620. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  57621. this._bodyUpdateRequired = false;
  57622. };
  57623. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  57624. if (this.object.getBoundingInfo) {
  57625. var q = this.object.rotationQuaternion;
  57626. //reset rotation
  57627. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  57628. //calculate the world matrix with no rotation
  57629. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  57630. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  57631. //bring back the rotation
  57632. this.object.rotationQuaternion = q;
  57633. //calculate the world matrix with the new rotation
  57634. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  57635. return size;
  57636. }
  57637. else {
  57638. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  57639. }
  57640. };
  57641. PhysicsImpostor.prototype.getObjectCenter = function () {
  57642. if (this.object.getBoundingInfo) {
  57643. return this.object.getBoundingInfo().boundingBox.centerWorld;
  57644. }
  57645. else {
  57646. return this.object.position;
  57647. }
  57648. };
  57649. /**
  57650. * Get a specific parametes from the options parameter.
  57651. */
  57652. PhysicsImpostor.prototype.getParam = function (paramName) {
  57653. return this._options[paramName];
  57654. };
  57655. /**
  57656. * Sets a specific parameter in the options given to the physics plugin
  57657. */
  57658. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  57659. this._options[paramName] = value;
  57660. this._bodyUpdateRequired = true;
  57661. };
  57662. /**
  57663. * Specifically change the body's mass option. Won't recreate the physics body object
  57664. */
  57665. PhysicsImpostor.prototype.setMass = function (mass) {
  57666. if (this.getParam("mass") !== mass) {
  57667. this.setParam("mass", mass);
  57668. }
  57669. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  57670. };
  57671. PhysicsImpostor.prototype.getLinearVelocity = function () {
  57672. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  57673. };
  57674. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  57675. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  57676. };
  57677. PhysicsImpostor.prototype.getAngularVelocity = function () {
  57678. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  57679. };
  57680. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  57681. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  57682. };
  57683. /**
  57684. * Execute a function with the physics plugin native code.
  57685. * Provide a function the will have two variables - the world object and the physics body object.
  57686. */
  57687. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  57688. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  57689. };
  57690. /**
  57691. * Register a function that will be executed before the physics world is stepping forward.
  57692. */
  57693. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  57694. this._onBeforePhysicsStepCallbacks.push(func);
  57695. };
  57696. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  57697. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  57698. if (index > -1) {
  57699. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  57700. }
  57701. else {
  57702. BABYLON.Tools.Warn("Function to remove was not found");
  57703. }
  57704. };
  57705. /**
  57706. * Register a function that will be executed after the physics step
  57707. */
  57708. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  57709. this._onAfterPhysicsStepCallbacks.push(func);
  57710. };
  57711. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  57712. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  57713. if (index > -1) {
  57714. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  57715. }
  57716. else {
  57717. BABYLON.Tools.Warn("Function to remove was not found");
  57718. }
  57719. };
  57720. /**
  57721. * register a function that will be executed when this impostor collides against a different body.
  57722. */
  57723. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  57724. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  57725. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  57726. };
  57727. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  57728. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  57729. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  57730. if (index > -1) {
  57731. this._onPhysicsCollideCallbacks.splice(index, 1);
  57732. }
  57733. else {
  57734. BABYLON.Tools.Warn("Function to remove was not found");
  57735. }
  57736. };
  57737. /**
  57738. * Apply a force
  57739. */
  57740. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  57741. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  57742. };
  57743. /**
  57744. * Apply an impulse
  57745. */
  57746. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  57747. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  57748. };
  57749. /**
  57750. * A help function to create a joint.
  57751. */
  57752. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  57753. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  57754. this.addJoint(otherImpostor, joint);
  57755. };
  57756. /**
  57757. * Add a joint to this impostor with a different impostor.
  57758. */
  57759. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  57760. this._joints.push({
  57761. otherImpostor: otherImpostor,
  57762. joint: joint
  57763. });
  57764. this._physicsEngine.addJoint(this, otherImpostor, joint);
  57765. };
  57766. /**
  57767. * Will keep this body still, in a sleep mode.
  57768. */
  57769. PhysicsImpostor.prototype.sleep = function () {
  57770. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  57771. };
  57772. /**
  57773. * Wake the body up.
  57774. */
  57775. PhysicsImpostor.prototype.wakeUp = function () {
  57776. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  57777. };
  57778. PhysicsImpostor.prototype.clone = function (newObject) {
  57779. if (!newObject)
  57780. return null;
  57781. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  57782. };
  57783. PhysicsImpostor.prototype.dispose = function () {
  57784. var _this = this;
  57785. //no dispose if no physics engine is available.
  57786. if (!this._physicsEngine) {
  57787. return;
  57788. }
  57789. this._joints.forEach(function (j) {
  57790. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  57791. });
  57792. //dispose the physics body
  57793. this._physicsEngine.removeImpostor(this);
  57794. if (this.parent) {
  57795. this.parent.forceUpdate();
  57796. }
  57797. else {
  57798. /*this._object.getChildMeshes().forEach(function(mesh) {
  57799. if (mesh.physicsImpostor) {
  57800. if (disposeChildren) {
  57801. mesh.physicsImpostor.dispose();
  57802. mesh.physicsImpostor = null;
  57803. }
  57804. }
  57805. })*/
  57806. }
  57807. };
  57808. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  57809. this._deltaPosition.copyFrom(position);
  57810. };
  57811. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  57812. if (!this._deltaRotation) {
  57813. this._deltaRotation = new BABYLON.Quaternion();
  57814. }
  57815. this._deltaRotation.copyFrom(rotation);
  57816. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  57817. };
  57818. return PhysicsImpostor;
  57819. }());
  57820. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  57821. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  57822. //Impostor types
  57823. PhysicsImpostor.NoImpostor = 0;
  57824. PhysicsImpostor.SphereImpostor = 1;
  57825. PhysicsImpostor.BoxImpostor = 2;
  57826. PhysicsImpostor.PlaneImpostor = 3;
  57827. PhysicsImpostor.MeshImpostor = 4;
  57828. PhysicsImpostor.CylinderImpostor = 7;
  57829. PhysicsImpostor.ParticleImpostor = 8;
  57830. PhysicsImpostor.HeightmapImpostor = 9;
  57831. BABYLON.PhysicsImpostor = PhysicsImpostor;
  57832. })(BABYLON || (BABYLON = {}));
  57833. //# sourceMappingURL=babylon.physicsImpostor.js.map
  57834. var BABYLON;
  57835. (function (BABYLON) {
  57836. var PhysicsEngine = (function () {
  57837. function PhysicsEngine(gravity, _physicsPlugin) {
  57838. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  57839. this._physicsPlugin = _physicsPlugin;
  57840. //new methods and parameters
  57841. this._impostors = [];
  57842. this._joints = [];
  57843. if (!this._physicsPlugin.isSupported()) {
  57844. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  57845. + "Please make sure it is included.");
  57846. }
  57847. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  57848. this.setGravity(gravity);
  57849. this.setTimeStep();
  57850. }
  57851. PhysicsEngine.prototype.setGravity = function (gravity) {
  57852. this.gravity = gravity;
  57853. this._physicsPlugin.setGravity(this.gravity);
  57854. };
  57855. /**
  57856. * Set the time step of the physics engine.
  57857. * default is 1/60.
  57858. * To slow it down, enter 1/600 for example.
  57859. * To speed it up, 1/30
  57860. * @param {number} newTimeStep the new timestep to apply to this world.
  57861. */
  57862. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  57863. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  57864. this._physicsPlugin.setTimeStep(newTimeStep);
  57865. };
  57866. PhysicsEngine.prototype.dispose = function () {
  57867. this._impostors.forEach(function (impostor) {
  57868. impostor.dispose();
  57869. });
  57870. this._physicsPlugin.dispose();
  57871. };
  57872. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  57873. return this._physicsPlugin.name;
  57874. };
  57875. /**
  57876. * Adding a new impostor for the impostor tracking.
  57877. * This will be done by the impostor itself.
  57878. * @param {PhysicsImpostor} impostor the impostor to add
  57879. */
  57880. PhysicsEngine.prototype.addImpostor = function (impostor) {
  57881. impostor.uniqueId = this._impostors.push(impostor);
  57882. //if no parent, generate the body
  57883. if (!impostor.parent) {
  57884. this._physicsPlugin.generatePhysicsBody(impostor);
  57885. }
  57886. };
  57887. /**
  57888. * Remove an impostor from the engine.
  57889. * This impostor and its mesh will not longer be updated by the physics engine.
  57890. * @param {PhysicsImpostor} impostor the impostor to remove
  57891. */
  57892. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  57893. var index = this._impostors.indexOf(impostor);
  57894. if (index > -1) {
  57895. var removed = this._impostors.splice(index, 1);
  57896. //Is it needed?
  57897. if (removed.length) {
  57898. //this will also remove it from the world.
  57899. removed[0].physicsBody = null;
  57900. }
  57901. }
  57902. };
  57903. /**
  57904. * Add a joint to the physics engine
  57905. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  57906. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  57907. * @param {PhysicsJoint} the joint that will connect both impostors.
  57908. */
  57909. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  57910. var impostorJoint = {
  57911. mainImpostor: mainImpostor,
  57912. connectedImpostor: connectedImpostor,
  57913. joint: joint
  57914. };
  57915. joint.physicsPlugin = this._physicsPlugin;
  57916. this._joints.push(impostorJoint);
  57917. this._physicsPlugin.generateJoint(impostorJoint);
  57918. };
  57919. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  57920. var matchingJoints = this._joints.filter(function (impostorJoint) {
  57921. return (impostorJoint.connectedImpostor === connectedImpostor
  57922. && impostorJoint.joint === joint
  57923. && impostorJoint.mainImpostor === mainImpostor);
  57924. });
  57925. if (matchingJoints.length) {
  57926. this._physicsPlugin.removeJoint(matchingJoints[0]);
  57927. //TODO remove it from the list as well
  57928. }
  57929. };
  57930. /**
  57931. * Called by the scene. no need to call it.
  57932. */
  57933. PhysicsEngine.prototype._step = function (delta) {
  57934. var _this = this;
  57935. //check if any mesh has no body / requires an update
  57936. this._impostors.forEach(function (impostor) {
  57937. if (impostor.isBodyInitRequired()) {
  57938. _this._physicsPlugin.generatePhysicsBody(impostor);
  57939. }
  57940. });
  57941. if (delta > 0.1) {
  57942. delta = 0.1;
  57943. }
  57944. else if (delta <= 0) {
  57945. delta = 1.0 / 60.0;
  57946. }
  57947. this._physicsPlugin.executeStep(delta, this._impostors);
  57948. };
  57949. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  57950. return this._physicsPlugin;
  57951. };
  57952. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  57953. for (var i = 0; i < this._impostors.length; ++i) {
  57954. if (this._impostors[i].object === object) {
  57955. return this._impostors[i];
  57956. }
  57957. }
  57958. };
  57959. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  57960. for (var i = 0; i < this._impostors.length; ++i) {
  57961. if (this._impostors[i].physicsBody === body) {
  57962. return this._impostors[i];
  57963. }
  57964. }
  57965. };
  57966. return PhysicsEngine;
  57967. }());
  57968. // Statics
  57969. PhysicsEngine.Epsilon = 0.001;
  57970. BABYLON.PhysicsEngine = PhysicsEngine;
  57971. })(BABYLON || (BABYLON = {}));
  57972. //# sourceMappingURL=babylon.physicsEngine.js.map
  57973. var BABYLON;
  57974. (function (BABYLON) {
  57975. var CannonJSPlugin = (function () {
  57976. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  57977. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  57978. if (iterations === void 0) { iterations = 10; }
  57979. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  57980. this.name = "CannonJSPlugin";
  57981. this._physicsMaterials = [];
  57982. this._fixedTimeStep = 1 / 60;
  57983. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  57984. this._currentCollisionGroup = 2;
  57985. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  57986. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  57987. this._tmpPosition = BABYLON.Vector3.Zero();
  57988. this._tmpQuaternion = new BABYLON.Quaternion();
  57989. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  57990. this._tmpDeltaRotation = new BABYLON.Quaternion();
  57991. this._tmpUnityRotation = new BABYLON.Quaternion();
  57992. if (!this.isSupported()) {
  57993. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  57994. return;
  57995. }
  57996. this.world = new CANNON.World();
  57997. this.world.broadphase = new CANNON.NaiveBroadphase();
  57998. this.world.solver.iterations = iterations;
  57999. }
  58000. CannonJSPlugin.prototype.setGravity = function (gravity) {
  58001. this.world.gravity.copy(gravity);
  58002. };
  58003. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  58004. this._fixedTimeStep = timeStep;
  58005. };
  58006. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  58007. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  58008. };
  58009. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  58010. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  58011. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  58012. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  58013. };
  58014. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  58015. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  58016. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  58017. impostor.physicsBody.applyForce(impulse, worldPoint);
  58018. };
  58019. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  58020. //parent-child relationship. Does this impostor has a parent impostor?
  58021. if (impostor.parent) {
  58022. if (impostor.physicsBody) {
  58023. this.removePhysicsBody(impostor);
  58024. //TODO is that needed?
  58025. impostor.forceUpdate();
  58026. }
  58027. return;
  58028. }
  58029. //should a new body be created for this impostor?
  58030. if (impostor.isBodyInitRequired()) {
  58031. var shape = this._createShape(impostor);
  58032. //unregister events, if body is being changed
  58033. var oldBody = impostor.physicsBody;
  58034. if (oldBody) {
  58035. this.removePhysicsBody(impostor);
  58036. }
  58037. //create the body and material
  58038. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  58039. var bodyCreationObject = {
  58040. mass: impostor.getParam("mass"),
  58041. material: material
  58042. };
  58043. // A simple extend, in case native options were used.
  58044. var nativeOptions = impostor.getParam("nativeOptions");
  58045. for (var key in nativeOptions) {
  58046. if (nativeOptions.hasOwnProperty(key)) {
  58047. bodyCreationObject[key] = nativeOptions[key];
  58048. }
  58049. }
  58050. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  58051. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  58052. this.world.addEventListener("preStep", impostor.beforeStep);
  58053. this.world.addEventListener("postStep", impostor.afterStep);
  58054. impostor.physicsBody.addShape(shape);
  58055. this.world.add(impostor.physicsBody);
  58056. //try to keep the body moving in the right direction by taking old properties.
  58057. //Should be tested!
  58058. if (oldBody) {
  58059. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  58060. impostor.physicsBody[param].copy(oldBody[param]);
  58061. });
  58062. }
  58063. this._processChildMeshes(impostor);
  58064. }
  58065. //now update the body's transformation
  58066. this._updatePhysicsBodyTransformation(impostor);
  58067. };
  58068. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  58069. var _this = this;
  58070. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  58071. if (meshChildren.length) {
  58072. var processMesh = function (localPosition, mesh) {
  58073. var childImpostor = mesh.getPhysicsImpostor();
  58074. if (childImpostor) {
  58075. var parent = childImpostor.parent;
  58076. if (parent !== mainImpostor) {
  58077. var localPosition = mesh.position;
  58078. if (childImpostor.physicsBody) {
  58079. _this.removePhysicsBody(childImpostor);
  58080. childImpostor.physicsBody = null;
  58081. }
  58082. childImpostor.parent = mainImpostor;
  58083. childImpostor.resetUpdateFlags();
  58084. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  58085. //Add the mass of the children.
  58086. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  58087. }
  58088. }
  58089. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  58090. };
  58091. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  58092. }
  58093. };
  58094. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  58095. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  58096. this.world.removeEventListener("preStep", impostor.beforeStep);
  58097. this.world.removeEventListener("postStep", impostor.afterStep);
  58098. this.world.remove(impostor.physicsBody);
  58099. };
  58100. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  58101. var mainBody = impostorJoint.mainImpostor.physicsBody;
  58102. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  58103. if (!mainBody || !connectedBody) {
  58104. return;
  58105. }
  58106. var constraint;
  58107. var jointData = impostorJoint.joint.jointData;
  58108. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  58109. var constraintData = {
  58110. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  58111. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  58112. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  58113. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  58114. maxForce: jointData.nativeParams.maxForce,
  58115. collideConnected: !!jointData.collision
  58116. };
  58117. switch (impostorJoint.joint.type) {
  58118. case BABYLON.PhysicsJoint.HingeJoint:
  58119. case BABYLON.PhysicsJoint.Hinge2Joint:
  58120. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  58121. break;
  58122. case BABYLON.PhysicsJoint.DistanceJoint:
  58123. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  58124. break;
  58125. case BABYLON.PhysicsJoint.SpringJoint:
  58126. var springData = jointData;
  58127. constraint = new CANNON.Spring(mainBody, connectedBody, {
  58128. restLength: springData.length,
  58129. stiffness: springData.stiffness,
  58130. damping: springData.damping,
  58131. localAnchorA: constraintData.pivotA,
  58132. localAnchorB: constraintData.pivotB
  58133. });
  58134. break;
  58135. case BABYLON.PhysicsJoint.LockJoint:
  58136. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  58137. break;
  58138. case BABYLON.PhysicsJoint.PointToPointJoint:
  58139. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  58140. default:
  58141. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  58142. break;
  58143. }
  58144. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  58145. constraint.collideConnected = !!jointData.collision;
  58146. impostorJoint.joint.physicsJoint = constraint;
  58147. //don't add spring as constraint, as it is not one.
  58148. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  58149. this.world.addConstraint(constraint);
  58150. }
  58151. else {
  58152. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  58153. constraint.applyForce();
  58154. });
  58155. }
  58156. };
  58157. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  58158. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  58159. };
  58160. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  58161. var index;
  58162. var mat;
  58163. for (index = 0; index < this._physicsMaterials.length; index++) {
  58164. mat = this._physicsMaterials[index];
  58165. if (mat.friction === friction && mat.restitution === restitution) {
  58166. return mat;
  58167. }
  58168. }
  58169. var currentMat = new CANNON.Material(name);
  58170. currentMat.friction = friction;
  58171. currentMat.restitution = restitution;
  58172. this._physicsMaterials.push(currentMat);
  58173. return currentMat;
  58174. };
  58175. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  58176. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  58177. };
  58178. CannonJSPlugin.prototype._createShape = function (impostor) {
  58179. var object = impostor.object;
  58180. var returnValue;
  58181. var extendSize = impostor.getObjectExtendSize();
  58182. switch (impostor.type) {
  58183. case BABYLON.PhysicsImpostor.SphereImpostor:
  58184. var radiusX = extendSize.x;
  58185. var radiusY = extendSize.y;
  58186. var radiusZ = extendSize.z;
  58187. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  58188. break;
  58189. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  58190. case BABYLON.PhysicsImpostor.CylinderImpostor:
  58191. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  58192. break;
  58193. case BABYLON.PhysicsImpostor.BoxImpostor:
  58194. var box = extendSize.scale(0.5);
  58195. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  58196. break;
  58197. case BABYLON.PhysicsImpostor.PlaneImpostor:
  58198. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  58199. returnValue = new CANNON.Plane();
  58200. break;
  58201. case BABYLON.PhysicsImpostor.MeshImpostor:
  58202. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  58203. var rawFaces = object.getIndices ? object.getIndices() : [];
  58204. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  58205. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  58206. break;
  58207. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  58208. returnValue = this._createHeightmap(object);
  58209. break;
  58210. case BABYLON.PhysicsImpostor.ParticleImpostor:
  58211. returnValue = new CANNON.Particle();
  58212. break;
  58213. }
  58214. return returnValue;
  58215. };
  58216. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  58217. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58218. var matrix = [];
  58219. //For now pointDepth will not be used and will be automatically calculated.
  58220. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  58221. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  58222. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  58223. var elementSize = dim * 2 / arraySize;
  58224. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  58225. for (var i = 0; i < pos.length; i = i + 3) {
  58226. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  58227. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  58228. var y = pos[i + 1] + minY;
  58229. if (!matrix[x]) {
  58230. matrix[x] = [];
  58231. }
  58232. if (!matrix[x][z]) {
  58233. matrix[x][z] = y;
  58234. }
  58235. matrix[x][z] = Math.max(y, matrix[x][z]);
  58236. }
  58237. for (var x = 0; x <= arraySize; ++x) {
  58238. if (!matrix[x]) {
  58239. var loc = 1;
  58240. while (!matrix[(x + loc) % arraySize]) {
  58241. loc++;
  58242. }
  58243. matrix[x] = matrix[(x + loc) % arraySize].slice();
  58244. //console.log("missing x", x);
  58245. }
  58246. for (var z = 0; z <= arraySize; ++z) {
  58247. if (!matrix[x][z]) {
  58248. var loc = 1;
  58249. var newValue;
  58250. while (newValue === undefined) {
  58251. newValue = matrix[x][(z + loc++) % arraySize];
  58252. }
  58253. matrix[x][z] = newValue;
  58254. }
  58255. }
  58256. }
  58257. var shape = new CANNON.Heightfield(matrix, {
  58258. elementSize: elementSize
  58259. });
  58260. //For future reference, needed for body transformation
  58261. shape.minY = minY;
  58262. return shape;
  58263. };
  58264. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  58265. var object = impostor.object;
  58266. //make sure it is updated...
  58267. object.computeWorldMatrix && object.computeWorldMatrix(true);
  58268. // The delta between the mesh position and the mesh bounding box center
  58269. var center = impostor.getObjectCenter();
  58270. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  58271. this._tmpPosition.copyFrom(center);
  58272. var quaternion = object.rotationQuaternion;
  58273. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  58274. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  58275. //-90 DEG in X, precalculated
  58276. quaternion = quaternion.multiply(this._minus90X);
  58277. //Invert! (Precalculated, 90 deg in X)
  58278. //No need to clone. this will never change.
  58279. impostor.setDeltaRotation(this._plus90X);
  58280. }
  58281. //If it is a heightfield, if should be centered.
  58282. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  58283. var mesh = object;
  58284. //calculate the correct body position:
  58285. var rotationQuaternion = mesh.rotationQuaternion;
  58286. mesh.rotationQuaternion = this._tmpUnityRotation;
  58287. mesh.computeWorldMatrix(true);
  58288. //get original center with no rotation
  58289. var c = center.clone();
  58290. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  58291. //rotation is back
  58292. mesh.rotationQuaternion = rotationQuaternion;
  58293. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  58294. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  58295. mesh.setPivotMatrix(p);
  58296. mesh.computeWorldMatrix(true);
  58297. //calculate the translation
  58298. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  58299. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  58300. //add it inverted to the delta
  58301. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  58302. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  58303. mesh.setPivotMatrix(oldPivot);
  58304. mesh.computeWorldMatrix(true);
  58305. }
  58306. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  58307. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  58308. this._tmpPosition.copyFrom(object.position);
  58309. }
  58310. impostor.setDeltaPosition(this._tmpDeltaPosition);
  58311. //Now update the impostor object
  58312. impostor.physicsBody.position.copy(this._tmpPosition);
  58313. impostor.physicsBody.quaternion.copy(quaternion);
  58314. };
  58315. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  58316. impostor.object.position.copyFrom(impostor.physicsBody.position);
  58317. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  58318. };
  58319. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  58320. impostor.physicsBody.position.copy(newPosition);
  58321. impostor.physicsBody.quaternion.copy(newRotation);
  58322. };
  58323. CannonJSPlugin.prototype.isSupported = function () {
  58324. return window.CANNON !== undefined;
  58325. };
  58326. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  58327. impostor.physicsBody.velocity.copy(velocity);
  58328. };
  58329. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  58330. impostor.physicsBody.angularVelocity.copy(velocity);
  58331. };
  58332. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  58333. var v = impostor.physicsBody.velocity;
  58334. if (!v)
  58335. return null;
  58336. return new BABYLON.Vector3(v.x, v.y, v.z);
  58337. };
  58338. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  58339. var v = impostor.physicsBody.angularVelocity;
  58340. if (!v)
  58341. return null;
  58342. return new BABYLON.Vector3(v.x, v.y, v.z);
  58343. };
  58344. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  58345. impostor.physicsBody.mass = mass;
  58346. impostor.physicsBody.updateMassProperties();
  58347. };
  58348. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  58349. impostor.physicsBody.sleep();
  58350. };
  58351. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  58352. impostor.physicsBody.wakeUp();
  58353. };
  58354. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  58355. joint.physicsJoint.distance = maxDistance;
  58356. };
  58357. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  58358. if (!motorIndex) {
  58359. joint.physicsJoint.enableMotor();
  58360. }
  58361. };
  58362. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  58363. if (!motorIndex) {
  58364. joint.physicsJoint.disableMotor();
  58365. }
  58366. };
  58367. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  58368. if (!motorIndex) {
  58369. joint.physicsJoint.enableMotor();
  58370. joint.physicsJoint.setMotorSpeed(speed);
  58371. if (maxForce) {
  58372. this.setLimit(joint, maxForce);
  58373. }
  58374. }
  58375. };
  58376. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  58377. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  58378. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  58379. };
  58380. CannonJSPlugin.prototype.dispose = function () {
  58381. //nothing to do, actually.
  58382. };
  58383. return CannonJSPlugin;
  58384. }());
  58385. BABYLON.CannonJSPlugin = CannonJSPlugin;
  58386. })(BABYLON || (BABYLON = {}));
  58387. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  58388. var BABYLON;
  58389. (function (BABYLON) {
  58390. var OimoJSPlugin = (function () {
  58391. function OimoJSPlugin(iterations) {
  58392. this.name = "OimoJSPlugin";
  58393. this._tmpImpostorsArray = [];
  58394. this._tmpPositionVector = BABYLON.Vector3.Zero();
  58395. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  58396. this.world.worldscale(1);
  58397. this.world.clear();
  58398. //making sure no stats are calculated
  58399. this.world.isNoStat = true;
  58400. }
  58401. OimoJSPlugin.prototype.setGravity = function (gravity) {
  58402. this.world.gravity.copy(gravity);
  58403. };
  58404. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  58405. this.world.timeStep = timeStep;
  58406. };
  58407. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  58408. var _this = this;
  58409. impostors.forEach(function (impostor) {
  58410. impostor.beforeStep();
  58411. });
  58412. this.world.step();
  58413. impostors.forEach(function (impostor) {
  58414. impostor.afterStep();
  58415. //update the ordered impostors array
  58416. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  58417. });
  58418. //check for collisions
  58419. var contact = this.world.contacts;
  58420. while (contact !== null) {
  58421. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  58422. contact = contact.next;
  58423. continue;
  58424. }
  58425. //is this body colliding with any other? get the impostor
  58426. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  58427. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  58428. if (!mainImpostor || !collidingImpostor) {
  58429. contact = contact.next;
  58430. continue;
  58431. }
  58432. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  58433. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  58434. contact = contact.next;
  58435. }
  58436. };
  58437. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  58438. var mass = impostor.physicsBody.massInfo.mass;
  58439. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  58440. };
  58441. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  58442. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  58443. this.applyImpulse(impostor, force, contactPoint);
  58444. };
  58445. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  58446. var _this = this;
  58447. //parent-child relationship. Does this impostor has a parent impostor?
  58448. if (impostor.parent) {
  58449. if (impostor.physicsBody) {
  58450. this.removePhysicsBody(impostor);
  58451. //TODO is that needed?
  58452. impostor.forceUpdate();
  58453. }
  58454. return;
  58455. }
  58456. if (impostor.isBodyInitRequired()) {
  58457. var bodyConfig = {
  58458. name: impostor.uniqueId,
  58459. //Oimo must have mass, also for static objects.
  58460. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  58461. size: [],
  58462. type: [],
  58463. pos: [],
  58464. rot: [],
  58465. move: impostor.getParam("mass") !== 0,
  58466. //Supporting older versions of Oimo
  58467. world: this.world
  58468. };
  58469. var impostors = [impostor];
  58470. var addToArray = function (parent) {
  58471. if (!parent.getChildMeshes)
  58472. return;
  58473. parent.getChildMeshes().forEach(function (m) {
  58474. if (m.physicsImpostor) {
  58475. impostors.push(m.physicsImpostor);
  58476. m.physicsImpostor._init();
  58477. }
  58478. });
  58479. };
  58480. addToArray(impostor.object);
  58481. var checkWithEpsilon_1 = function (value) {
  58482. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  58483. };
  58484. impostors.forEach(function (i) {
  58485. //get the correct bounding box
  58486. var oldQuaternion = i.object.rotationQuaternion;
  58487. var rot = new OIMO.Euler().setFromQuaternion({
  58488. x: impostor.object.rotationQuaternion.x,
  58489. y: impostor.object.rotationQuaternion.y,
  58490. z: impostor.object.rotationQuaternion.z,
  58491. s: impostor.object.rotationQuaternion.w
  58492. });
  58493. var extendSize = i.getObjectExtendSize();
  58494. if (i === impostor) {
  58495. var center = impostor.getObjectCenter();
  58496. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  58497. //Can also use Array.prototype.push.apply
  58498. bodyConfig.pos.push(center.x);
  58499. bodyConfig.pos.push(center.y);
  58500. bodyConfig.pos.push(center.z);
  58501. //tmp solution
  58502. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  58503. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  58504. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  58505. }
  58506. else {
  58507. bodyConfig.pos.push(i.object.position.x);
  58508. bodyConfig.pos.push(i.object.position.y);
  58509. bodyConfig.pos.push(i.object.position.z);
  58510. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  58511. bodyConfig.rot.push(0);
  58512. bodyConfig.rot.push(0);
  58513. bodyConfig.rot.push(0);
  58514. }
  58515. // register mesh
  58516. switch (i.type) {
  58517. case BABYLON.PhysicsImpostor.ParticleImpostor:
  58518. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  58519. case BABYLON.PhysicsImpostor.SphereImpostor:
  58520. var radiusX = extendSize.x;
  58521. var radiusY = extendSize.y;
  58522. var radiusZ = extendSize.z;
  58523. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  58524. bodyConfig.type.push('sphere');
  58525. //due to the way oimo works with compounds, add 3 times
  58526. bodyConfig.size.push(size);
  58527. bodyConfig.size.push(size);
  58528. bodyConfig.size.push(size);
  58529. break;
  58530. case BABYLON.PhysicsImpostor.CylinderImpostor:
  58531. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  58532. var sizeY = checkWithEpsilon_1(extendSize.y);
  58533. bodyConfig.type.push('cylinder');
  58534. bodyConfig.size.push(sizeX);
  58535. bodyConfig.size.push(sizeY);
  58536. //due to the way oimo works with compounds, add one more value.
  58537. bodyConfig.size.push(sizeY);
  58538. break;
  58539. case BABYLON.PhysicsImpostor.PlaneImpostor:
  58540. case BABYLON.PhysicsImpostor.BoxImpostor:
  58541. default:
  58542. var sizeX = checkWithEpsilon_1(extendSize.x);
  58543. var sizeY = checkWithEpsilon_1(extendSize.y);
  58544. var sizeZ = checkWithEpsilon_1(extendSize.z);
  58545. bodyConfig.type.push('box');
  58546. bodyConfig.size.push(sizeX);
  58547. bodyConfig.size.push(sizeY);
  58548. bodyConfig.size.push(sizeZ);
  58549. break;
  58550. }
  58551. //actually not needed, but hey...
  58552. i.object.rotationQuaternion = oldQuaternion;
  58553. });
  58554. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  58555. }
  58556. else {
  58557. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  58558. }
  58559. impostor.setDeltaPosition(this._tmpPositionVector);
  58560. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  58561. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  58562. };
  58563. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  58564. //impostor.physicsBody.dispose();
  58565. //Same as : (older oimo versions)
  58566. this.world.removeRigidBody(impostor.physicsBody);
  58567. };
  58568. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  58569. var mainBody = impostorJoint.mainImpostor.physicsBody;
  58570. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  58571. if (!mainBody || !connectedBody) {
  58572. return;
  58573. }
  58574. var jointData = impostorJoint.joint.jointData;
  58575. var options = jointData.nativeParams || {};
  58576. var type;
  58577. var nativeJointData = {
  58578. body1: mainBody,
  58579. body2: connectedBody,
  58580. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  58581. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  58582. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  58583. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  58584. min: options.min,
  58585. max: options.max,
  58586. collision: options.collision || jointData.collision,
  58587. spring: options.spring,
  58588. //supporting older version of Oimo
  58589. world: this.world
  58590. };
  58591. switch (impostorJoint.joint.type) {
  58592. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  58593. type = "jointBall";
  58594. break;
  58595. case BABYLON.PhysicsJoint.SpringJoint:
  58596. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  58597. var springData = jointData;
  58598. nativeJointData.min = springData.length || nativeJointData.min;
  58599. //Max should also be set, just make sure it is at least min
  58600. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  58601. case BABYLON.PhysicsJoint.DistanceJoint:
  58602. type = "jointDistance";
  58603. nativeJointData.max = jointData.maxDistance;
  58604. break;
  58605. case BABYLON.PhysicsJoint.PrismaticJoint:
  58606. type = "jointPrisme";
  58607. break;
  58608. case BABYLON.PhysicsJoint.SliderJoint:
  58609. type = "jointSlide";
  58610. break;
  58611. case BABYLON.PhysicsJoint.WheelJoint:
  58612. type = "jointWheel";
  58613. break;
  58614. case BABYLON.PhysicsJoint.HingeJoint:
  58615. default:
  58616. type = "jointHinge";
  58617. break;
  58618. }
  58619. nativeJointData.type = type;
  58620. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  58621. };
  58622. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  58623. //Bug in Oimo prevents us from disposing a joint in the playground
  58624. //joint.joint.physicsJoint.dispose();
  58625. //So we will bruteforce it!
  58626. try {
  58627. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  58628. }
  58629. catch (e) {
  58630. BABYLON.Tools.Warn(e);
  58631. }
  58632. };
  58633. OimoJSPlugin.prototype.isSupported = function () {
  58634. return OIMO !== undefined;
  58635. };
  58636. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  58637. if (!impostor.physicsBody.sleeping) {
  58638. //TODO check that
  58639. if (impostor.physicsBody.shapes.next) {
  58640. var parentShape = this._getLastShape(impostor.physicsBody);
  58641. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  58642. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  58643. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  58644. }
  58645. else {
  58646. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  58647. }
  58648. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  58649. impostor.object.rotationQuaternion.normalize();
  58650. }
  58651. };
  58652. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  58653. var body = impostor.physicsBody;
  58654. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  58655. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  58656. body.syncShapes();
  58657. body.awake();
  58658. };
  58659. OimoJSPlugin.prototype._getLastShape = function (body) {
  58660. var lastShape = body.shapes;
  58661. while (lastShape.next) {
  58662. lastShape = lastShape.next;
  58663. }
  58664. return lastShape;
  58665. };
  58666. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  58667. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  58668. };
  58669. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  58670. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  58671. };
  58672. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  58673. var v = impostor.physicsBody.linearVelocity;
  58674. if (!v)
  58675. return null;
  58676. return new BABYLON.Vector3(v.x, v.y, v.z);
  58677. };
  58678. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  58679. var v = impostor.physicsBody.angularVelocity;
  58680. if (!v)
  58681. return null;
  58682. return new BABYLON.Vector3(v.x, v.y, v.z);
  58683. };
  58684. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  58685. var staticBody = mass === 0;
  58686. //this will actually set the body's density and not its mass.
  58687. //But this is how oimo treats the mass variable.
  58688. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  58689. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  58690. };
  58691. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  58692. impostor.physicsBody.sleep();
  58693. };
  58694. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  58695. impostor.physicsBody.awake();
  58696. };
  58697. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  58698. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  58699. if (minDistance !== void 0) {
  58700. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  58701. }
  58702. };
  58703. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  58704. //TODO separate rotational and transational motors.
  58705. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  58706. if (motor) {
  58707. motor.setMotor(speed, maxForce);
  58708. }
  58709. };
  58710. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  58711. //TODO separate rotational and transational motors.
  58712. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  58713. if (motor) {
  58714. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  58715. }
  58716. };
  58717. OimoJSPlugin.prototype.dispose = function () {
  58718. this.world.clear();
  58719. };
  58720. return OimoJSPlugin;
  58721. }());
  58722. BABYLON.OimoJSPlugin = OimoJSPlugin;
  58723. })(BABYLON || (BABYLON = {}));
  58724. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  58725. var BABYLON;
  58726. (function (BABYLON) {
  58727. var Internals;
  58728. (function (Internals) {
  58729. /*
  58730. * Based on jsTGALoader - Javascript loader for TGA file
  58731. * By Vincent Thibault
  58732. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  58733. */
  58734. var TGATools = (function () {
  58735. function TGATools() {
  58736. }
  58737. TGATools.GetTGAHeader = function (data) {
  58738. var offset = 0;
  58739. var header = {
  58740. id_length: data[offset++],
  58741. colormap_type: data[offset++],
  58742. image_type: data[offset++],
  58743. colormap_index: data[offset++] | data[offset++] << 8,
  58744. colormap_length: data[offset++] | data[offset++] << 8,
  58745. colormap_size: data[offset++],
  58746. origin: [
  58747. data[offset++] | data[offset++] << 8,
  58748. data[offset++] | data[offset++] << 8
  58749. ],
  58750. width: data[offset++] | data[offset++] << 8,
  58751. height: data[offset++] | data[offset++] << 8,
  58752. pixel_size: data[offset++],
  58753. flags: data[offset++]
  58754. };
  58755. return header;
  58756. };
  58757. TGATools.UploadContent = function (gl, data) {
  58758. // Not enough data to contain header ?
  58759. if (data.length < 19) {
  58760. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  58761. return;
  58762. }
  58763. // Read Header
  58764. var offset = 18;
  58765. var header = TGATools.GetTGAHeader(data);
  58766. // Assume it's a valid Targa file.
  58767. if (header.id_length + offset > data.length) {
  58768. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  58769. return;
  58770. }
  58771. // Skip not needed data
  58772. offset += header.id_length;
  58773. var use_rle = false;
  58774. var use_pal = false;
  58775. var use_rgb = false;
  58776. var use_grey = false;
  58777. // Get some informations.
  58778. switch (header.image_type) {
  58779. case TGATools._TYPE_RLE_INDEXED:
  58780. use_rle = true;
  58781. case TGATools._TYPE_INDEXED:
  58782. use_pal = true;
  58783. break;
  58784. case TGATools._TYPE_RLE_RGB:
  58785. use_rle = true;
  58786. case TGATools._TYPE_RGB:
  58787. use_rgb = true;
  58788. break;
  58789. case TGATools._TYPE_RLE_GREY:
  58790. use_rle = true;
  58791. case TGATools._TYPE_GREY:
  58792. use_grey = true;
  58793. break;
  58794. }
  58795. var pixel_data;
  58796. var numAlphaBits = header.flags & 0xf;
  58797. var pixel_size = header.pixel_size >> 3;
  58798. var pixel_total = header.width * header.height * pixel_size;
  58799. // Read palettes
  58800. var palettes;
  58801. if (use_pal) {
  58802. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  58803. }
  58804. // Read LRE
  58805. if (use_rle) {
  58806. pixel_data = new Uint8Array(pixel_total);
  58807. var c, count, i;
  58808. var localOffset = 0;
  58809. var pixels = new Uint8Array(pixel_size);
  58810. while (offset < pixel_total && localOffset < pixel_total) {
  58811. c = data[offset++];
  58812. count = (c & 0x7f) + 1;
  58813. // RLE pixels
  58814. if (c & 0x80) {
  58815. // Bind pixel tmp array
  58816. for (i = 0; i < pixel_size; ++i) {
  58817. pixels[i] = data[offset++];
  58818. }
  58819. // Copy pixel array
  58820. for (i = 0; i < count; ++i) {
  58821. pixel_data.set(pixels, localOffset + i * pixel_size);
  58822. }
  58823. localOffset += pixel_size * count;
  58824. }
  58825. else {
  58826. count *= pixel_size;
  58827. for (i = 0; i < count; ++i) {
  58828. pixel_data[localOffset + i] = data[offset++];
  58829. }
  58830. localOffset += count;
  58831. }
  58832. }
  58833. }
  58834. else {
  58835. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  58836. }
  58837. // Load to texture
  58838. var x_start, y_start, x_step, y_step, y_end, x_end;
  58839. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  58840. default:
  58841. case TGATools._ORIGIN_UL:
  58842. x_start = 0;
  58843. x_step = 1;
  58844. x_end = header.width;
  58845. y_start = 0;
  58846. y_step = 1;
  58847. y_end = header.height;
  58848. break;
  58849. case TGATools._ORIGIN_BL:
  58850. x_start = 0;
  58851. x_step = 1;
  58852. x_end = header.width;
  58853. y_start = header.height - 1;
  58854. y_step = -1;
  58855. y_end = -1;
  58856. break;
  58857. case TGATools._ORIGIN_UR:
  58858. x_start = header.width - 1;
  58859. x_step = -1;
  58860. x_end = -1;
  58861. y_start = 0;
  58862. y_step = 1;
  58863. y_end = header.height;
  58864. break;
  58865. case TGATools._ORIGIN_BR:
  58866. x_start = header.width - 1;
  58867. x_step = -1;
  58868. x_end = -1;
  58869. y_start = header.height - 1;
  58870. y_step = -1;
  58871. y_end = -1;
  58872. break;
  58873. }
  58874. // Load the specify method
  58875. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  58876. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  58877. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  58878. };
  58879. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58880. var image = pixel_data, colormap = palettes;
  58881. var width = header.width, height = header.height;
  58882. var color, i = 0, x, y;
  58883. var imageData = new Uint8Array(width * height * 4);
  58884. for (y = y_start; y !== y_end; y += y_step) {
  58885. for (x = x_start; x !== x_end; x += x_step, i++) {
  58886. color = image[i];
  58887. imageData[(x + width * y) * 4 + 3] = 255;
  58888. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  58889. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  58890. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  58891. }
  58892. }
  58893. return imageData;
  58894. };
  58895. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58896. var image = pixel_data;
  58897. var width = header.width, height = header.height;
  58898. var color, i = 0, x, y;
  58899. var imageData = new Uint8Array(width * height * 4);
  58900. for (y = y_start; y !== y_end; y += y_step) {
  58901. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  58902. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  58903. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  58904. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  58905. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  58906. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  58907. }
  58908. }
  58909. return imageData;
  58910. };
  58911. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58912. var image = pixel_data;
  58913. var width = header.width, height = header.height;
  58914. var i = 0, x, y;
  58915. var imageData = new Uint8Array(width * height * 4);
  58916. for (y = y_start; y !== y_end; y += y_step) {
  58917. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  58918. imageData[(x + width * y) * 4 + 3] = 255;
  58919. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  58920. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  58921. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  58922. }
  58923. }
  58924. return imageData;
  58925. };
  58926. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58927. var image = pixel_data;
  58928. var width = header.width, height = header.height;
  58929. var i = 0, x, y;
  58930. var imageData = new Uint8Array(width * height * 4);
  58931. for (y = y_start; y !== y_end; y += y_step) {
  58932. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  58933. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  58934. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  58935. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  58936. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  58937. }
  58938. }
  58939. return imageData;
  58940. };
  58941. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58942. var image = pixel_data;
  58943. var width = header.width, height = header.height;
  58944. var color, i = 0, x, y;
  58945. var imageData = new Uint8Array(width * height * 4);
  58946. for (y = y_start; y !== y_end; y += y_step) {
  58947. for (x = x_start; x !== x_end; x += x_step, i++) {
  58948. color = image[i];
  58949. imageData[(x + width * y) * 4 + 0] = color;
  58950. imageData[(x + width * y) * 4 + 1] = color;
  58951. imageData[(x + width * y) * 4 + 2] = color;
  58952. imageData[(x + width * y) * 4 + 3] = 255;
  58953. }
  58954. }
  58955. return imageData;
  58956. };
  58957. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58958. var image = pixel_data;
  58959. var width = header.width, height = header.height;
  58960. var i = 0, x, y;
  58961. var imageData = new Uint8Array(width * height * 4);
  58962. for (y = y_start; y !== y_end; y += y_step) {
  58963. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  58964. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  58965. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  58966. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  58967. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  58968. }
  58969. }
  58970. return imageData;
  58971. };
  58972. return TGATools;
  58973. }());
  58974. TGATools._TYPE_NO_DATA = 0;
  58975. TGATools._TYPE_INDEXED = 1;
  58976. TGATools._TYPE_RGB = 2;
  58977. TGATools._TYPE_GREY = 3;
  58978. TGATools._TYPE_RLE_INDEXED = 9;
  58979. TGATools._TYPE_RLE_RGB = 10;
  58980. TGATools._TYPE_RLE_GREY = 11;
  58981. TGATools._ORIGIN_MASK = 0x30;
  58982. TGATools._ORIGIN_SHIFT = 0x04;
  58983. TGATools._ORIGIN_BL = 0x00;
  58984. TGATools._ORIGIN_BR = 0x01;
  58985. TGATools._ORIGIN_UL = 0x02;
  58986. TGATools._ORIGIN_UR = 0x03;
  58987. Internals.TGATools = TGATools;
  58988. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58989. })(BABYLON || (BABYLON = {}));
  58990. //# sourceMappingURL=babylon.tga.js.map
  58991. var BABYLON;
  58992. (function (BABYLON) {
  58993. var Internals;
  58994. (function (Internals) {
  58995. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  58996. // All values and structures referenced from:
  58997. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  58998. var DDS_MAGIC = 0x20534444;
  58999. 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;
  59000. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  59001. 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;
  59002. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  59003. function FourCCToInt32(value) {
  59004. return value.charCodeAt(0) +
  59005. (value.charCodeAt(1) << 8) +
  59006. (value.charCodeAt(2) << 16) +
  59007. (value.charCodeAt(3) << 24);
  59008. }
  59009. function Int32ToFourCC(value) {
  59010. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  59011. }
  59012. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  59013. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  59014. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  59015. var headerLengthInt = 31; // The header length in 32 bit ints
  59016. // Offsets into the header array
  59017. var off_magic = 0;
  59018. var off_size = 1;
  59019. var off_flags = 2;
  59020. var off_height = 3;
  59021. var off_width = 4;
  59022. var off_mipmapCount = 7;
  59023. var off_pfFlags = 20;
  59024. var off_pfFourCC = 21;
  59025. var off_RGBbpp = 22;
  59026. var off_RMask = 23;
  59027. var off_GMask = 24;
  59028. var off_BMask = 25;
  59029. var off_AMask = 26;
  59030. var off_caps1 = 27;
  59031. var off_caps2 = 28;
  59032. ;
  59033. var DDSTools = (function () {
  59034. function DDSTools() {
  59035. }
  59036. DDSTools.GetDDSInfo = function (arrayBuffer) {
  59037. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  59038. var mipmapCount = 1;
  59039. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  59040. mipmapCount = Math.max(1, header[off_mipmapCount]);
  59041. }
  59042. return {
  59043. width: header[off_width],
  59044. height: header[off_height],
  59045. mipmapCount: mipmapCount,
  59046. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  59047. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  59048. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  59049. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  59050. };
  59051. };
  59052. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  59053. var byteArray = new Uint8Array(dataLength);
  59054. var srcData = new Uint8Array(arrayBuffer);
  59055. var index = 0;
  59056. for (var y = height - 1; y >= 0; y--) {
  59057. for (var x = 0; x < width; x++) {
  59058. var srcPos = dataOffset + (x + y * width) * 4;
  59059. byteArray[index + 2] = srcData[srcPos];
  59060. byteArray[index + 1] = srcData[srcPos + 1];
  59061. byteArray[index] = srcData[srcPos + 2];
  59062. byteArray[index + 3] = srcData[srcPos + 3];
  59063. index += 4;
  59064. }
  59065. }
  59066. return byteArray;
  59067. };
  59068. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  59069. var byteArray = new Uint8Array(dataLength);
  59070. var srcData = new Uint8Array(arrayBuffer);
  59071. var index = 0;
  59072. for (var y = height - 1; y >= 0; y--) {
  59073. for (var x = 0; x < width; x++) {
  59074. var srcPos = dataOffset + (x + y * width) * 3;
  59075. byteArray[index + 2] = srcData[srcPos];
  59076. byteArray[index + 1] = srcData[srcPos + 1];
  59077. byteArray[index] = srcData[srcPos + 2];
  59078. index += 3;
  59079. }
  59080. }
  59081. return byteArray;
  59082. };
  59083. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  59084. var byteArray = new Uint8Array(dataLength);
  59085. var srcData = new Uint8Array(arrayBuffer);
  59086. var index = 0;
  59087. for (var y = height - 1; y >= 0; y--) {
  59088. for (var x = 0; x < width; x++) {
  59089. var srcPos = dataOffset + (x + y * width);
  59090. byteArray[index] = srcData[srcPos];
  59091. index++;
  59092. }
  59093. }
  59094. return byteArray;
  59095. };
  59096. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  59097. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  59098. if (header[off_magic] != DDS_MAGIC) {
  59099. BABYLON.Tools.Error("Invalid magic number in DDS header");
  59100. return;
  59101. }
  59102. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  59103. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  59104. return;
  59105. }
  59106. if (info.isFourCC) {
  59107. fourCC = header[off_pfFourCC];
  59108. switch (fourCC) {
  59109. case FOURCC_DXT1:
  59110. blockBytes = 8;
  59111. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  59112. break;
  59113. case FOURCC_DXT3:
  59114. blockBytes = 16;
  59115. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  59116. break;
  59117. case FOURCC_DXT5:
  59118. blockBytes = 16;
  59119. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  59120. break;
  59121. default:
  59122. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  59123. return;
  59124. }
  59125. }
  59126. mipmapCount = 1;
  59127. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  59128. mipmapCount = Math.max(1, header[off_mipmapCount]);
  59129. }
  59130. var bpp = header[off_RGBbpp];
  59131. for (var face = 0; face < faces; face++) {
  59132. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  59133. width = header[off_width];
  59134. height = header[off_height];
  59135. dataOffset = header[off_size] + 4;
  59136. for (i = 0; i < mipmapCount; ++i) {
  59137. if (info.isRGB) {
  59138. if (bpp === 24) {
  59139. dataLength = width * height * 3;
  59140. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  59141. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  59142. }
  59143. else {
  59144. dataLength = width * height * 4;
  59145. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  59146. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  59147. }
  59148. }
  59149. else if (info.isLuminance) {
  59150. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  59151. var unpaddedRowSize = width;
  59152. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  59153. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  59154. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  59155. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  59156. }
  59157. else {
  59158. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  59159. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  59160. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  59161. }
  59162. dataOffset += dataLength;
  59163. width *= 0.5;
  59164. height *= 0.5;
  59165. width = Math.max(1.0, width);
  59166. height = Math.max(1.0, height);
  59167. }
  59168. }
  59169. };
  59170. return DDSTools;
  59171. }());
  59172. Internals.DDSTools = DDSTools;
  59173. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59174. })(BABYLON || (BABYLON = {}));
  59175. //# sourceMappingURL=babylon.dds.js.map
  59176. var BABYLON;
  59177. (function (BABYLON) {
  59178. var Internals;
  59179. (function (Internals) {
  59180. /**
  59181. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  59182. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  59183. */
  59184. var KhronosTextureContainer = (function () {
  59185. /**
  59186. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  59187. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  59188. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  59189. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  59190. */
  59191. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  59192. this.arrayBuffer = arrayBuffer;
  59193. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  59194. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  59195. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  59196. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  59197. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  59198. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  59199. BABYLON.Tools.Error("texture missing KTX identifier");
  59200. return;
  59201. }
  59202. // load the reset of the header in native 32 bit int
  59203. var header = new Int32Array(this.arrayBuffer, 12, 13);
  59204. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  59205. var oppositeEndianess = header[0] === 0x01020304;
  59206. // read all the header elements in order they exist in the file, without modification (sans endainness)
  59207. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  59208. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  59209. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  59210. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  59211. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  59212. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  59213. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  59214. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  59215. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  59216. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  59217. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  59218. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  59219. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  59220. if (this.glType !== 0) {
  59221. BABYLON.Tools.Error("only compressed formats currently supported");
  59222. return;
  59223. }
  59224. else {
  59225. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  59226. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  59227. }
  59228. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  59229. BABYLON.Tools.Error("only 2D textures currently supported");
  59230. return;
  59231. }
  59232. if (this.numberOfArrayElements !== 0) {
  59233. BABYLON.Tools.Error("texture arrays not currently supported");
  59234. return;
  59235. }
  59236. if (this.numberOfFaces !== facesExpected) {
  59237. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  59238. return;
  59239. }
  59240. // we now have a completely validated file, so could use existence of loadType as success
  59241. // would need to make this more elaborate & adjust checks above to support more than one load type
  59242. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  59243. }
  59244. // not as fast hardware based, but will probably never need to use
  59245. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  59246. return ((val & 0xFF) << 24)
  59247. | ((val & 0xFF00) << 8)
  59248. | ((val >> 8) & 0xFF00)
  59249. | ((val >> 24) & 0xFF);
  59250. };
  59251. /**
  59252. * It is assumed that the texture has already been created & is currently bound
  59253. */
  59254. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  59255. switch (this.loadType) {
  59256. case KhronosTextureContainer.COMPRESSED_2D:
  59257. this._upload2DCompressedLevels(gl, loadMipmaps);
  59258. break;
  59259. case KhronosTextureContainer.TEX_2D:
  59260. case KhronosTextureContainer.COMPRESSED_3D:
  59261. case KhronosTextureContainer.TEX_3D:
  59262. }
  59263. };
  59264. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  59265. // initialize width & height for level 1
  59266. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  59267. var width = this.pixelWidth;
  59268. var height = this.pixelHeight;
  59269. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  59270. for (var level = 0; level < mipmapCount; level++) {
  59271. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  59272. for (var face = 0; face < this.numberOfFaces; face++) {
  59273. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  59274. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  59275. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  59276. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  59277. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  59278. }
  59279. width = Math.max(1.0, width * 0.5);
  59280. height = Math.max(1.0, height * 0.5);
  59281. }
  59282. };
  59283. return KhronosTextureContainer;
  59284. }());
  59285. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  59286. // load types
  59287. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  59288. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  59289. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  59290. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  59291. Internals.KhronosTextureContainer = KhronosTextureContainer;
  59292. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59293. })(BABYLON || (BABYLON = {}));
  59294. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  59295. var BABYLON;
  59296. (function (BABYLON) {
  59297. var DynamicFloatArrayElementInfo = (function () {
  59298. function DynamicFloatArrayElementInfo() {
  59299. }
  59300. return DynamicFloatArrayElementInfo;
  59301. }());
  59302. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  59303. /**
  59304. * 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.
  59305. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  59306. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  59307. * 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.
  59308. * 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.
  59309. * 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".
  59310. */
  59311. var DynamicFloatArray = (function () {
  59312. /**
  59313. * Construct an instance of the dynamic float array
  59314. * @param stride size of one element in float (i.e. not bytes!)
  59315. * @param initialElementCount the number of available entries at construction
  59316. */
  59317. function DynamicFloatArray(stride, initialElementCount) {
  59318. this.compareValueOffset = null;
  59319. this.sortingAscending = true;
  59320. this._stride = stride;
  59321. this.buffer = new Float32Array(stride * initialElementCount);
  59322. this._lastUsed = 0;
  59323. this._firstFree = 0;
  59324. this._allEntries = new Array(initialElementCount);
  59325. this._freeEntries = new Array(initialElementCount);
  59326. for (var i = 0; i < initialElementCount; i++) {
  59327. var element = new DynamicFloatArrayElementInfo();
  59328. element.offset = i * stride;
  59329. this._allEntries[i] = element;
  59330. this._freeEntries[initialElementCount - i - 1] = element;
  59331. }
  59332. }
  59333. /**
  59334. * Allocate an element in the array.
  59335. * @return the element info instance that contains the offset into the main buffer of the element's location.
  59336. * Beware, this offset may change when you call pack()
  59337. */
  59338. DynamicFloatArray.prototype.allocElement = function () {
  59339. if (this._freeEntries.length === 0) {
  59340. this._growBuffer();
  59341. }
  59342. var el = this._freeEntries.pop();
  59343. this._lastUsed = Math.max(el.offset, this._lastUsed);
  59344. if (el.offset === this._firstFree) {
  59345. if (this._freeEntries.length > 0) {
  59346. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  59347. }
  59348. else {
  59349. this._firstFree += this._stride;
  59350. }
  59351. }
  59352. return el;
  59353. };
  59354. /**
  59355. * Free the element corresponding to the given element info
  59356. * @param elInfo the element that describe the allocated element
  59357. */
  59358. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  59359. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  59360. this._freeEntries.push(elInfo);
  59361. };
  59362. /**
  59363. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  59364. * 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().
  59365. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  59366. */
  59367. DynamicFloatArray.prototype.pack = function () {
  59368. // no free slot? no need to pack
  59369. if (this._freeEntries.length === 0) {
  59370. return this.buffer;
  59371. }
  59372. // If the buffer is already packed the last used will always be lower than the first free
  59373. // 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.
  59374. if (this._lastUsed < this._firstFree) {
  59375. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  59376. return elementsBuffer_1;
  59377. }
  59378. var s = this._stride;
  59379. // 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
  59380. var lastFree = new DynamicFloatArrayElementInfo();
  59381. lastFree.offset = this.totalElementCount * s;
  59382. this._freeEntries.push(lastFree);
  59383. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  59384. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  59385. var firstFreeSlotOffset = sortedFree[0].offset;
  59386. var freeZoneSize = 1;
  59387. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  59388. var prevOffset = sortedFree[0].offset;
  59389. for (var i = 1; i < sortedFree.length; i++) {
  59390. // 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
  59391. if (firstFreeSlotOffset >= occupiedZoneSize) {
  59392. break;
  59393. }
  59394. var curFree = sortedFree[i];
  59395. var curOffset = curFree.offset;
  59396. // Compute the distance between this offset and the previous
  59397. var distance = curOffset - prevOffset;
  59398. // If the distance is the stride size, they are adjacent, it good, move to the next
  59399. if (distance === s) {
  59400. // Free zone is one element bigger
  59401. ++freeZoneSize;
  59402. // as we're about to iterate to the next, the cur becomes the previous...
  59403. prevOffset = curOffset;
  59404. continue;
  59405. }
  59406. // Distance is bigger, which means there's x element between the previous free and this one
  59407. var usedRange = (distance / s) - 1;
  59408. // Two cases the free zone is smaller than the data to move or bigger
  59409. // Copy what can fit in the free zone
  59410. var curMoveOffset = curOffset - s;
  59411. var copyCount = Math.min(freeZoneSize, usedRange);
  59412. for (var j = 0; j < copyCount; j++) {
  59413. var freeI = firstFreeSlotOffset / s;
  59414. var curI = curMoveOffset / s;
  59415. var moveEl = sortedAll[curI];
  59416. this._moveElement(moveEl, firstFreeSlotOffset);
  59417. var replacedEl = sortedAll[freeI];
  59418. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  59419. replacedEl.offset = curMoveOffset;
  59420. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  59421. sortedAll[freeI] = moveEl;
  59422. sortedAll[curI] = replacedEl;
  59423. curMoveOffset -= s;
  59424. firstFreeSlotOffset += s;
  59425. }
  59426. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  59427. if (freeZoneSize <= usedRange) {
  59428. firstFreeSlotOffset = curMoveOffset + s;
  59429. freeZoneSize = 1 + copyCount;
  59430. }
  59431. else {
  59432. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  59433. }
  59434. // as we're about to iterate to the next, the cur becomes the previous...
  59435. prevOffset = curOffset;
  59436. }
  59437. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  59438. this._lastUsed = firstFreeSlotOffset - s;
  59439. this._firstFree = firstFreeSlotOffset;
  59440. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  59441. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  59442. this._allEntries = sortedAll;
  59443. return elementsBuffer;
  59444. };
  59445. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  59446. for (var i = 0; i < this._stride; i++) {
  59447. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  59448. }
  59449. element.offset = destOffset;
  59450. };
  59451. DynamicFloatArray.prototype._growBuffer = function () {
  59452. // Allocate the new buffer with 50% more entries, copy the content of the current one
  59453. var newElCount = Math.floor(this.totalElementCount * 1.5);
  59454. var newBuffer = new Float32Array(newElCount * this._stride);
  59455. newBuffer.set(this.buffer);
  59456. var curCount = this.totalElementCount;
  59457. var addedCount = newElCount - this.totalElementCount;
  59458. for (var i = 0; i < addedCount; i++) {
  59459. var element = new DynamicFloatArrayElementInfo();
  59460. element.offset = (curCount + i) * this.stride;
  59461. this._allEntries.push(element);
  59462. this._freeEntries[addedCount - i - 1] = element;
  59463. }
  59464. this._firstFree = curCount * this.stride;
  59465. this.buffer = newBuffer;
  59466. };
  59467. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  59468. /**
  59469. * Get the total count of entries that can fit in the current buffer
  59470. * @returns the elements count
  59471. */
  59472. get: function () {
  59473. return this._allEntries.length;
  59474. },
  59475. enumerable: true,
  59476. configurable: true
  59477. });
  59478. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  59479. /**
  59480. * Get the count of free entries that can still be allocated without resizing the buffer
  59481. * @returns the free elements count
  59482. */
  59483. get: function () {
  59484. return this._freeEntries.length;
  59485. },
  59486. enumerable: true,
  59487. configurable: true
  59488. });
  59489. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  59490. /**
  59491. * Get the count of allocated elements
  59492. * @returns the allocated elements count
  59493. */
  59494. get: function () {
  59495. return this._allEntries.length - this._freeEntries.length;
  59496. },
  59497. enumerable: true,
  59498. configurable: true
  59499. });
  59500. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  59501. /**
  59502. * Return the size of one element in float
  59503. * @returns the size in float
  59504. */
  59505. get: function () {
  59506. return this._stride;
  59507. },
  59508. enumerable: true,
  59509. configurable: true
  59510. });
  59511. DynamicFloatArray.prototype.sort = function () {
  59512. var _this = this;
  59513. if (!this.compareValueOffset) {
  59514. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  59515. }
  59516. var count = this.usedElementCount;
  59517. // Do we have to (re)create the sort table?
  59518. if (!this._sortTable || this._sortTable.length < count) {
  59519. // 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...
  59520. var newCount = Math.min(this.totalElementCount, count * 2);
  59521. this._sortTable = new Array(newCount);
  59522. }
  59523. if (!this._sortedTable || this._sortedTable.length !== count) {
  59524. this._sortedTable = new Array(count);
  59525. }
  59526. // Because, you know...
  59527. this.pack();
  59528. //let stride = this.stride;
  59529. //for (let i = 0; i < count; i++) {
  59530. // let si = this._sortTable[i];
  59531. // if (!si) {
  59532. // si = new SortInfo();
  59533. // this._sortTable[i] = si;
  59534. // }
  59535. // si.entry = this._allEntries[i];
  59536. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  59537. // si.swapedOffset = null;
  59538. // this._sortedTable[i] = si;
  59539. //}
  59540. var curOffset = 0;
  59541. var stride = this.stride;
  59542. for (var i = 0; i < count; i++, curOffset += stride) {
  59543. var si = this._sortTable[i];
  59544. if (!si) {
  59545. si = new SortInfo();
  59546. this._sortTable[i] = si;
  59547. }
  59548. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  59549. si.offset = curOffset;
  59550. si.swapedOffset = null;
  59551. this._sortedTable[i] = si;
  59552. }
  59553. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  59554. if (this.sortingAscending) {
  59555. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  59556. }
  59557. else {
  59558. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  59559. }
  59560. var swapElements = function (src, dst) {
  59561. for (var i = 0; i < stride; i++) {
  59562. var tps = _this.buffer[dst + i];
  59563. _this.buffer[dst + i] = _this.buffer[src + i];
  59564. _this.buffer[src + i] = tps;
  59565. }
  59566. };
  59567. // 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:
  59568. // 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),
  59569. // and I still want something with a good algorithm complexity.
  59570. // 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,
  59571. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  59572. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  59573. // 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
  59574. // until we find a SortInfo object without a swapedOffset which means we got the right location
  59575. // 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
  59576. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  59577. for (var i = 0; i < count; i++) {
  59578. // Get the element to move
  59579. var sourceSI = this._sortedTable[i];
  59580. var destSI = this._sortTable[i];
  59581. var sourceOff = sourceSI.offset;
  59582. // If the source changed location, find the new one
  59583. if (sourceSI.swapedOffset) {
  59584. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  59585. var curSI = sourceSI;
  59586. while (curSI.swapedOffset) {
  59587. curSI = this._sortTable[curSI.swapedOffset / stride];
  59588. }
  59589. // Finally get the right location
  59590. sourceOff = curSI.offset;
  59591. }
  59592. // Tag the element being replaced with its new location
  59593. destSI.swapedOffset = sourceOff;
  59594. // Swap elements (only if needed)
  59595. if (sourceOff !== destSI.offset) {
  59596. swapElements(sourceOff, destSI.offset);
  59597. }
  59598. // Update the offset in the corresponding DFAE
  59599. //sourceSI.entry.offset = destSI.entry.offset;
  59600. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  59601. }
  59602. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  59603. return true;
  59604. };
  59605. return DynamicFloatArray;
  59606. }());
  59607. BABYLON.DynamicFloatArray = DynamicFloatArray;
  59608. var SortInfo = (function () {
  59609. function SortInfo() {
  59610. this.compareData = this.offset = this.swapedOffset = null;
  59611. }
  59612. return SortInfo;
  59613. }());
  59614. })(BABYLON || (BABYLON = {}));
  59615. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  59616. var BABYLON;
  59617. (function (BABYLON) {
  59618. var Debug;
  59619. (function (Debug) {
  59620. /**
  59621. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  59622. */
  59623. var SkeletonViewer = (function () {
  59624. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  59625. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59626. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59627. this.skeleton = skeleton;
  59628. this.mesh = mesh;
  59629. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59630. this.renderingGroupId = renderingGroupId;
  59631. this.color = BABYLON.Color3.White();
  59632. this._debugLines = [];
  59633. this._isEnabled = false;
  59634. this._scene = scene;
  59635. this.update();
  59636. this._renderFunction = this.update.bind(this);
  59637. }
  59638. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59639. get: function () {
  59640. return this._isEnabled;
  59641. },
  59642. set: function (value) {
  59643. if (this._isEnabled === value) {
  59644. return;
  59645. }
  59646. this._isEnabled = value;
  59647. if (value) {
  59648. this._scene.registerBeforeRender(this._renderFunction);
  59649. }
  59650. else {
  59651. this._scene.unregisterBeforeRender(this._renderFunction);
  59652. }
  59653. },
  59654. enumerable: true,
  59655. configurable: true
  59656. });
  59657. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59658. if (x === void 0) { x = 0; }
  59659. if (y === void 0) { y = 0; }
  59660. if (z === void 0) { z = 0; }
  59661. var tmat = BABYLON.Tmp.Matrix[0];
  59662. var parentBone = bone.getParent();
  59663. tmat.copyFrom(bone.getLocalMatrix());
  59664. if (x !== 0 || y !== 0 || z !== 0) {
  59665. var tmat2 = BABYLON.Tmp.Matrix[1];
  59666. BABYLON.Matrix.IdentityToRef(tmat2);
  59667. tmat2.m[12] = x;
  59668. tmat2.m[13] = y;
  59669. tmat2.m[14] = z;
  59670. tmat2.multiplyToRef(tmat, tmat);
  59671. }
  59672. if (parentBone) {
  59673. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59674. }
  59675. tmat.multiplyToRef(meshMat, tmat);
  59676. position.x = tmat.m[12];
  59677. position.y = tmat.m[13];
  59678. position.z = tmat.m[14];
  59679. };
  59680. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59681. var len = bones.length;
  59682. var meshPos = this.mesh.position;
  59683. for (var i = 0; i < len; i++) {
  59684. var bone = bones[i];
  59685. var points = this._debugLines[i];
  59686. if (!points) {
  59687. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59688. this._debugLines[i] = points;
  59689. }
  59690. this._getBonePosition(points[0], bone, meshMat);
  59691. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59692. points[0].subtractInPlace(meshPos);
  59693. points[1].subtractInPlace(meshPos);
  59694. }
  59695. };
  59696. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59697. var len = bones.length;
  59698. var boneNum = 0;
  59699. var meshPos = this.mesh.position;
  59700. for (var i = len - 1; i >= 0; i--) {
  59701. var childBone = bones[i];
  59702. var parentBone = childBone.getParent();
  59703. if (!parentBone) {
  59704. continue;
  59705. }
  59706. var points = this._debugLines[boneNum];
  59707. if (!points) {
  59708. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59709. this._debugLines[boneNum] = points;
  59710. }
  59711. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  59712. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  59713. points[0].subtractInPlace(meshPos);
  59714. points[1].subtractInPlace(meshPos);
  59715. boneNum++;
  59716. }
  59717. };
  59718. SkeletonViewer.prototype.update = function () {
  59719. if (this.autoUpdateBonesMatrices) {
  59720. this.skeleton.computeAbsoluteTransforms();
  59721. }
  59722. if (this.skeleton.bones[0].length === undefined) {
  59723. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59724. }
  59725. else {
  59726. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59727. }
  59728. if (!this._debugMesh) {
  59729. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  59730. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59731. }
  59732. else {
  59733. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59734. }
  59735. this._debugMesh.position.copyFrom(this.mesh.position);
  59736. this._debugMesh.color = this.color;
  59737. };
  59738. SkeletonViewer.prototype.dispose = function () {
  59739. if (this._debugMesh) {
  59740. this.isEnabled = false;
  59741. this._debugMesh.dispose();
  59742. this._debugMesh = null;
  59743. }
  59744. };
  59745. return SkeletonViewer;
  59746. }());
  59747. Debug.SkeletonViewer = SkeletonViewer;
  59748. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59749. })(BABYLON || (BABYLON = {}));
  59750. //# sourceMappingURL=babylon.skeletonViewer.js.map
  59751. var BABYLON;
  59752. (function (BABYLON) {
  59753. var Debug;
  59754. (function (Debug) {
  59755. var AxesViewer = (function () {
  59756. function AxesViewer(scene, scaleLines) {
  59757. if (scaleLines === void 0) { scaleLines = 1; }
  59758. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59759. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59760. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59761. this.scaleLines = 1;
  59762. this.scaleLines = scaleLines;
  59763. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  59764. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  59765. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  59766. this._xmesh.renderingGroupId = 2;
  59767. this._ymesh.renderingGroupId = 2;
  59768. this._zmesh.renderingGroupId = 2;
  59769. this._xmesh.material.checkReadyOnlyOnce = true;
  59770. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  59771. this._ymesh.material.checkReadyOnlyOnce = true;
  59772. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  59773. this._zmesh.material.checkReadyOnlyOnce = true;
  59774. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  59775. this.scene = scene;
  59776. }
  59777. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  59778. var scaleLines = this.scaleLines;
  59779. this._xmesh.position.copyFrom(position);
  59780. this._ymesh.position.copyFrom(position);
  59781. this._zmesh.position.copyFrom(position);
  59782. var point2 = this._xline[1];
  59783. point2.x = xaxis.x * scaleLines;
  59784. point2.y = xaxis.y * scaleLines;
  59785. point2.z = xaxis.z * scaleLines;
  59786. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  59787. point2 = this._yline[1];
  59788. point2.x = yaxis.x * scaleLines;
  59789. point2.y = yaxis.y * scaleLines;
  59790. point2.z = yaxis.z * scaleLines;
  59791. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  59792. point2 = this._zline[1];
  59793. point2.x = zaxis.x * scaleLines;
  59794. point2.y = zaxis.y * scaleLines;
  59795. point2.z = zaxis.z * scaleLines;
  59796. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  59797. };
  59798. AxesViewer.prototype.dispose = function () {
  59799. if (this._xmesh) {
  59800. this._xmesh.dispose();
  59801. this._ymesh.dispose();
  59802. this._zmesh.dispose();
  59803. this._xmesh = null;
  59804. this._ymesh = null;
  59805. this._zmesh = null;
  59806. this._xline = null;
  59807. this._yline = null;
  59808. this._zline = null;
  59809. this.scene = null;
  59810. }
  59811. };
  59812. return AxesViewer;
  59813. }());
  59814. Debug.AxesViewer = AxesViewer;
  59815. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59816. })(BABYLON || (BABYLON = {}));
  59817. //# sourceMappingURL=babylon.axesViewer.js.map
  59818. var BABYLON;
  59819. (function (BABYLON) {
  59820. var Debug;
  59821. (function (Debug) {
  59822. var BoneAxesViewer = (function (_super) {
  59823. __extends(BoneAxesViewer, _super);
  59824. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  59825. if (scaleLines === void 0) { scaleLines = 1; }
  59826. var _this = _super.call(this, scene, scaleLines) || this;
  59827. _this.pos = BABYLON.Vector3.Zero();
  59828. _this.xaxis = BABYLON.Vector3.Zero();
  59829. _this.yaxis = BABYLON.Vector3.Zero();
  59830. _this.zaxis = BABYLON.Vector3.Zero();
  59831. _this.mesh = mesh;
  59832. _this.bone = bone;
  59833. return _this;
  59834. }
  59835. BoneAxesViewer.prototype.update = function () {
  59836. var bone = this.bone;
  59837. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  59838. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  59839. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  59840. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  59841. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  59842. };
  59843. BoneAxesViewer.prototype.dispose = function () {
  59844. if (this.pos) {
  59845. this.pos = null;
  59846. this.xaxis = null;
  59847. this.yaxis = null;
  59848. this.zaxis = null;
  59849. this.mesh = null;
  59850. this.bone = null;
  59851. _super.prototype.dispose.call(this);
  59852. }
  59853. };
  59854. return BoneAxesViewer;
  59855. }(Debug.AxesViewer));
  59856. Debug.BoneAxesViewer = BoneAxesViewer;
  59857. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59858. })(BABYLON || (BABYLON = {}));
  59859. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  59860. var BABYLON;
  59861. (function (BABYLON) {
  59862. var RayHelper = (function () {
  59863. function RayHelper(ray) {
  59864. this.ray = ray;
  59865. }
  59866. RayHelper.CreateAndShow = function (ray, scene, color) {
  59867. var helper = new RayHelper(ray);
  59868. helper.show(scene, color);
  59869. return helper;
  59870. };
  59871. RayHelper.prototype.show = function (scene, color) {
  59872. if (!this._renderFunction) {
  59873. var ray = this.ray;
  59874. this._renderFunction = this._render.bind(this);
  59875. this._scene = scene;
  59876. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  59877. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  59878. this._scene.registerBeforeRender(this._renderFunction);
  59879. }
  59880. if (color) {
  59881. this._renderLine.color.copyFrom(color);
  59882. }
  59883. };
  59884. RayHelper.prototype.hide = function () {
  59885. if (this._renderFunction) {
  59886. this._scene.unregisterBeforeRender(this._renderFunction);
  59887. this._scene = null;
  59888. this._renderFunction = null;
  59889. this._renderLine.dispose();
  59890. this._renderLine = null;
  59891. this._renderPoints = null;
  59892. }
  59893. };
  59894. RayHelper.prototype._render = function () {
  59895. var ray = this.ray;
  59896. var point = this._renderPoints[1];
  59897. var len = Math.min(ray.length, 1000000);
  59898. point.copyFrom(ray.direction);
  59899. point.scaleInPlace(len);
  59900. point.addInPlace(ray.origin);
  59901. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  59902. };
  59903. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  59904. this._attachedToMesh = mesh;
  59905. var ray = this.ray;
  59906. if (!ray.direction) {
  59907. ray.direction = BABYLON.Vector3.Zero();
  59908. }
  59909. if (!ray.origin) {
  59910. ray.origin = BABYLON.Vector3.Zero();
  59911. }
  59912. if (length) {
  59913. ray.length = length;
  59914. }
  59915. if (!meshSpaceOrigin) {
  59916. meshSpaceOrigin = BABYLON.Vector3.Zero();
  59917. }
  59918. if (!meshSpaceDirection) {
  59919. // -1 so that this will work with Mesh.lookAt
  59920. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  59921. }
  59922. if (!this._meshSpaceDirection) {
  59923. this._meshSpaceDirection = meshSpaceDirection.clone();
  59924. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  59925. }
  59926. else {
  59927. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  59928. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  59929. }
  59930. if (!this._updateToMeshFunction) {
  59931. this._updateToMeshFunction = this._updateToMesh.bind(this);
  59932. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  59933. }
  59934. this._updateToMesh();
  59935. };
  59936. RayHelper.prototype.detachFromMesh = function () {
  59937. if (this._attachedToMesh) {
  59938. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  59939. this._attachedToMesh = null;
  59940. this._updateToMeshFunction = null;
  59941. }
  59942. };
  59943. RayHelper.prototype._updateToMesh = function () {
  59944. var ray = this.ray;
  59945. if (this._attachedToMesh._isDisposed) {
  59946. this.detachFromMesh();
  59947. return;
  59948. }
  59949. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  59950. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  59951. };
  59952. RayHelper.prototype.dispose = function () {
  59953. this.hide();
  59954. this.detachFromMesh();
  59955. this.ray = null;
  59956. };
  59957. return RayHelper;
  59958. }());
  59959. BABYLON.RayHelper = RayHelper;
  59960. })(BABYLON || (BABYLON = {}));
  59961. //# sourceMappingURL=babylon.rayHelper.js.map
  59962. var BABYLON;
  59963. (function (BABYLON) {
  59964. var DebugLayer = (function () {
  59965. function DebugLayer(scene) {
  59966. this._scene = scene;
  59967. }
  59968. /** Creates the inspector window. */
  59969. DebugLayer.prototype._createInspector = function (config) {
  59970. if (config === void 0) { config = {}; }
  59971. var popup = config.popup || false;
  59972. var initialTab = config.initialTab || 0;
  59973. var parentElement = config.parentElement || null;
  59974. if (!this._inspector) {
  59975. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  59976. } // else nothing to do,; instance is already existing
  59977. };
  59978. DebugLayer.prototype.isVisible = function () {
  59979. if (!this._inspector) {
  59980. return false;
  59981. }
  59982. return true;
  59983. };
  59984. DebugLayer.prototype.hide = function () {
  59985. if (this._inspector) {
  59986. try {
  59987. this._inspector.dispose();
  59988. }
  59989. catch (e) {
  59990. // If the inspector has been removed directly from the inspector tool
  59991. }
  59992. this._inspector = null;
  59993. }
  59994. };
  59995. DebugLayer.prototype.show = function (config) {
  59996. if (config === void 0) { config = {}; }
  59997. if (typeof INSPECTOR == 'undefined') {
  59998. // Load inspector and add it to the DOM
  59999. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60000. }
  60001. else {
  60002. // Otherwise creates the inspector
  60003. this._createInspector(config);
  60004. }
  60005. };
  60006. return DebugLayer;
  60007. }());
  60008. // Get protocol used - http or https
  60009. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  60010. BABYLON.DebugLayer = DebugLayer;
  60011. })(BABYLON || (BABYLON = {}));
  60012. //# sourceMappingURL=babylon.debugLayer.js.map
  60013. var BABYLON;
  60014. (function (BABYLON) {
  60015. var BoundingBoxRenderer = (function () {
  60016. function BoundingBoxRenderer(scene) {
  60017. this.frontColor = new BABYLON.Color3(1, 1, 1);
  60018. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  60019. this.showBackLines = true;
  60020. this.renderList = new BABYLON.SmartArray(32);
  60021. this._vertexBuffers = {};
  60022. this._scene = scene;
  60023. }
  60024. BoundingBoxRenderer.prototype._prepareRessources = function () {
  60025. if (this._colorShader) {
  60026. return;
  60027. }
  60028. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  60029. attributes: [BABYLON.VertexBuffer.PositionKind],
  60030. uniforms: ["world", "viewProjection", "color"]
  60031. });
  60032. var engine = this._scene.getEngine();
  60033. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  60034. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  60035. 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]);
  60036. };
  60037. BoundingBoxRenderer.prototype.reset = function () {
  60038. this.renderList.reset();
  60039. };
  60040. BoundingBoxRenderer.prototype.render = function () {
  60041. if (this.renderList.length === 0) {
  60042. return;
  60043. }
  60044. this._prepareRessources();
  60045. if (!this._colorShader.isReady()) {
  60046. return;
  60047. }
  60048. var engine = this._scene.getEngine();
  60049. engine.setDepthWrite(false);
  60050. this._colorShader._preBind();
  60051. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  60052. var boundingBox = this.renderList.data[boundingBoxIndex];
  60053. var min = boundingBox.minimum;
  60054. var max = boundingBox.maximum;
  60055. var diff = max.subtract(min);
  60056. var median = min.add(diff.scale(0.5));
  60057. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60058. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60059. .multiply(boundingBox.getWorldMatrix());
  60060. // VBOs
  60061. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60062. if (this.showBackLines) {
  60063. // Back
  60064. engine.setDepthFunctionToGreaterOrEqual();
  60065. this._scene.resetCachedMaterial();
  60066. this._colorShader.setColor4("color", this.backColor.toColor4());
  60067. this._colorShader.bind(worldMatrix);
  60068. // Draw order
  60069. engine.draw(false, 0, 24);
  60070. }
  60071. // Front
  60072. engine.setDepthFunctionToLess();
  60073. this._scene.resetCachedMaterial();
  60074. this._colorShader.setColor4("color", this.frontColor.toColor4());
  60075. this._colorShader.bind(worldMatrix);
  60076. // Draw order
  60077. engine.draw(false, 0, 24);
  60078. }
  60079. this._colorShader.unbind();
  60080. engine.setDepthFunctionToLessOrEqual();
  60081. engine.setDepthWrite(true);
  60082. };
  60083. BoundingBoxRenderer.prototype.dispose = function () {
  60084. if (!this._colorShader) {
  60085. return;
  60086. }
  60087. this.renderList.dispose();
  60088. this._colorShader.dispose();
  60089. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60090. if (buffer) {
  60091. buffer.dispose();
  60092. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60093. }
  60094. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60095. };
  60096. return BoundingBoxRenderer;
  60097. }());
  60098. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  60099. })(BABYLON || (BABYLON = {}));
  60100. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  60101. var BABYLON;
  60102. (function (BABYLON) {
  60103. var MorphTarget = (function () {
  60104. function MorphTarget(name, influence) {
  60105. if (influence === void 0) { influence = 0; }
  60106. this.name = name;
  60107. this.animations = new Array();
  60108. this.onInfluenceChanged = new BABYLON.Observable();
  60109. this.influence = influence;
  60110. }
  60111. Object.defineProperty(MorphTarget.prototype, "influence", {
  60112. get: function () {
  60113. return this._influence;
  60114. },
  60115. set: function (influence) {
  60116. if (this._influence === influence) {
  60117. return;
  60118. }
  60119. var previous = this._influence;
  60120. this._influence = influence;
  60121. if (this.onInfluenceChanged.hasObservers) {
  60122. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  60123. }
  60124. },
  60125. enumerable: true,
  60126. configurable: true
  60127. });
  60128. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  60129. get: function () {
  60130. return this._normals !== undefined;
  60131. },
  60132. enumerable: true,
  60133. configurable: true
  60134. });
  60135. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  60136. get: function () {
  60137. return this._tangents !== undefined;
  60138. },
  60139. enumerable: true,
  60140. configurable: true
  60141. });
  60142. MorphTarget.prototype.setPositions = function (data) {
  60143. this._positions = new Float32Array(data);
  60144. };
  60145. MorphTarget.prototype.getPositions = function () {
  60146. return this._positions;
  60147. };
  60148. MorphTarget.prototype.setNormals = function (data) {
  60149. this._normals = new Float32Array(data);
  60150. };
  60151. MorphTarget.prototype.getNormals = function () {
  60152. return this._normals;
  60153. };
  60154. MorphTarget.prototype.setTangents = function (data) {
  60155. this._tangents = new Float32Array(data);
  60156. };
  60157. MorphTarget.prototype.getTangents = function () {
  60158. return this._tangents;
  60159. };
  60160. /**
  60161. * Serializes the current target into a Serialization object.
  60162. * Returns the serialized object.
  60163. */
  60164. MorphTarget.prototype.serialize = function () {
  60165. var serializationObject = {};
  60166. serializationObject.name = this.name;
  60167. serializationObject.influence = this.influence;
  60168. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  60169. if (this.hasNormals) {
  60170. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  60171. }
  60172. if (this.hasTangents) {
  60173. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  60174. }
  60175. return serializationObject;
  60176. };
  60177. // Statics
  60178. MorphTarget.Parse = function (serializationObject) {
  60179. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  60180. result.setPositions(serializationObject.positions);
  60181. if (serializationObject.normals) {
  60182. result.setNormals(serializationObject.normals);
  60183. }
  60184. if (serializationObject.tangents) {
  60185. result.setTangents(serializationObject.tangents);
  60186. }
  60187. return result;
  60188. };
  60189. MorphTarget.FromMesh = function (mesh, name, influence) {
  60190. if (!name) {
  60191. name = mesh.name;
  60192. }
  60193. var result = new MorphTarget(name, influence);
  60194. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  60195. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  60196. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  60197. }
  60198. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  60199. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  60200. }
  60201. return result;
  60202. };
  60203. return MorphTarget;
  60204. }());
  60205. BABYLON.MorphTarget = MorphTarget;
  60206. })(BABYLON || (BABYLON = {}));
  60207. //# sourceMappingURL=babylon.morphTarget.js.map
  60208. var BABYLON;
  60209. (function (BABYLON) {
  60210. var MorphTargetManager = (function () {
  60211. function MorphTargetManager(scene) {
  60212. this._targets = new Array();
  60213. this._targetObservable = new Array();
  60214. this._activeTargets = new BABYLON.SmartArray(16);
  60215. this._supportsNormals = false;
  60216. this._supportsTangents = false;
  60217. this._vertexCount = 0;
  60218. this._uniqueId = 0;
  60219. if (!scene) {
  60220. scene = BABYLON.Engine.LastCreatedScene;
  60221. }
  60222. this._scene = scene;
  60223. this._scene.morphTargetManagers.push(this);
  60224. this._uniqueId = scene.getUniqueId();
  60225. }
  60226. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  60227. get: function () {
  60228. return this._uniqueId;
  60229. },
  60230. enumerable: true,
  60231. configurable: true
  60232. });
  60233. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  60234. get: function () {
  60235. return this._vertexCount;
  60236. },
  60237. enumerable: true,
  60238. configurable: true
  60239. });
  60240. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  60241. get: function () {
  60242. return this._supportsNormals;
  60243. },
  60244. enumerable: true,
  60245. configurable: true
  60246. });
  60247. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  60248. get: function () {
  60249. return this._supportsTangents;
  60250. },
  60251. enumerable: true,
  60252. configurable: true
  60253. });
  60254. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  60255. get: function () {
  60256. return this._targets.length;
  60257. },
  60258. enumerable: true,
  60259. configurable: true
  60260. });
  60261. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  60262. get: function () {
  60263. return this._activeTargets.length;
  60264. },
  60265. enumerable: true,
  60266. configurable: true
  60267. });
  60268. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  60269. get: function () {
  60270. return this._influences;
  60271. },
  60272. enumerable: true,
  60273. configurable: true
  60274. });
  60275. MorphTargetManager.prototype.getActiveTarget = function (index) {
  60276. return this._activeTargets.data[index];
  60277. };
  60278. MorphTargetManager.prototype.getTarget = function (index) {
  60279. return this._targets[index];
  60280. };
  60281. MorphTargetManager.prototype.addTarget = function (target) {
  60282. var _this = this;
  60283. if (this._vertexCount) {
  60284. if (this._vertexCount !== target.getPositions().length / 3) {
  60285. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  60286. return;
  60287. }
  60288. }
  60289. this._targets.push(target);
  60290. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  60291. _this._syncActiveTargets(needUpdate);
  60292. }));
  60293. this._syncActiveTargets(true);
  60294. };
  60295. MorphTargetManager.prototype.removeTarget = function (target) {
  60296. var index = this._targets.indexOf(target);
  60297. if (index >= 0) {
  60298. this._targets.splice(index, 1);
  60299. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  60300. this._vertexCount = 0;
  60301. this._syncActiveTargets(true);
  60302. }
  60303. };
  60304. /**
  60305. * Serializes the current manager into a Serialization object.
  60306. * Returns the serialized object.
  60307. */
  60308. MorphTargetManager.prototype.serialize = function () {
  60309. var serializationObject = {};
  60310. serializationObject.id = this.uniqueId;
  60311. serializationObject.targets = [];
  60312. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  60313. var target = _a[_i];
  60314. serializationObject.targets.push(target.serialize());
  60315. }
  60316. return serializationObject;
  60317. };
  60318. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  60319. this._syncActiveTargets(needUpdate);
  60320. };
  60321. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  60322. this._activeTargets.reset();
  60323. var tempInfluences = [];
  60324. this._supportsNormals = true;
  60325. this._supportsTangents = true;
  60326. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  60327. var target = _a[_i];
  60328. if (target.influence > 0) {
  60329. this._activeTargets.push(target);
  60330. tempInfluences.push(target.influence);
  60331. this._supportsNormals = this._supportsNormals && target.hasNormals;
  60332. this._supportsTangents = this._supportsTangents && target.hasTangents;
  60333. if (this._vertexCount === 0) {
  60334. this._vertexCount = target.getPositions().length / 3;
  60335. }
  60336. }
  60337. }
  60338. this._influences = new Float32Array(tempInfluences);
  60339. if (needUpdate) {
  60340. // Flag meshes as dirty to resync with the active targets
  60341. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  60342. var mesh = _c[_b];
  60343. if (mesh.morphTargetManager === this) {
  60344. mesh._syncGeometryWithMorphTargetManager();
  60345. }
  60346. }
  60347. }
  60348. };
  60349. // Statics
  60350. MorphTargetManager.Parse = function (serializationObject, scene) {
  60351. var result = new MorphTargetManager(scene);
  60352. result._uniqueId = serializationObject.id;
  60353. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  60354. var targetData = _a[_i];
  60355. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  60356. }
  60357. return result;
  60358. };
  60359. return MorphTargetManager;
  60360. }());
  60361. BABYLON.MorphTargetManager = MorphTargetManager;
  60362. })(BABYLON || (BABYLON = {}));
  60363. //# sourceMappingURL=babylon.morphTargetManager.js.map
  60364. var BABYLON;
  60365. (function (BABYLON) {
  60366. /**
  60367. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  60368. * It can help converting any input color in a desired output one. This can then be used to create effects
  60369. * from sepia, black and white to sixties or futuristic rendering...
  60370. *
  60371. * The only supported format is currently 3dl.
  60372. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  60373. */
  60374. var ColorGradingTexture = (function (_super) {
  60375. __extends(ColorGradingTexture, _super);
  60376. /**
  60377. * Instantiates a ColorGradingTexture from the following parameters.
  60378. *
  60379. * @param url The location of the color gradind data (currently only supporting 3dl)
  60380. * @param scene The scene the texture will be used in
  60381. */
  60382. function ColorGradingTexture(url, scene) {
  60383. var _this = _super.call(this, scene) || this;
  60384. if (!url) {
  60385. return _this;
  60386. }
  60387. _this._textureMatrix = BABYLON.Matrix.Identity();
  60388. _this.name = url;
  60389. _this.url = url;
  60390. _this.hasAlpha = false;
  60391. _this.isCube = false;
  60392. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60393. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60394. _this.anisotropicFilteringLevel = 1;
  60395. _this._texture = _this._getFromCache(url, true);
  60396. if (!_this._texture) {
  60397. if (!scene.useDelayedTextureLoading) {
  60398. _this.loadTexture();
  60399. }
  60400. else {
  60401. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  60402. }
  60403. }
  60404. return _this;
  60405. }
  60406. /**
  60407. * Returns the texture matrix used in most of the material.
  60408. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  60409. */
  60410. ColorGradingTexture.prototype.getTextureMatrix = function () {
  60411. return this._textureMatrix;
  60412. };
  60413. /**
  60414. * Occurs when the file being loaded is a .3dl LUT file.
  60415. */
  60416. ColorGradingTexture.prototype.load3dlTexture = function () {
  60417. var _this = this;
  60418. var mipLevels = 0;
  60419. var floatArrayView = null;
  60420. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60421. this._texture = texture;
  60422. var callback = function (text) {
  60423. var data;
  60424. var tempData;
  60425. var line;
  60426. var lines = text.split('\n');
  60427. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  60428. var maxColor = 0;
  60429. for (var i = 0; i < lines.length; i++) {
  60430. line = lines[i];
  60431. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  60432. continue;
  60433. if (line.indexOf('#') === 0)
  60434. continue;
  60435. var words = line.split(" ");
  60436. if (size === 0) {
  60437. // Number of space + one
  60438. size = words.length;
  60439. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  60440. tempData = new Float32Array(size * size * size * 4);
  60441. continue;
  60442. }
  60443. if (size != 0) {
  60444. var r = Math.max(parseInt(words[0]), 0);
  60445. var g = Math.max(parseInt(words[1]), 0);
  60446. var b = Math.max(parseInt(words[2]), 0);
  60447. maxColor = Math.max(r, maxColor);
  60448. maxColor = Math.max(g, maxColor);
  60449. maxColor = Math.max(b, maxColor);
  60450. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  60451. tempData[pixelStorageIndex + 0] = r;
  60452. tempData[pixelStorageIndex + 1] = g;
  60453. tempData[pixelStorageIndex + 2] = b;
  60454. tempData[pixelStorageIndex + 3] = 0;
  60455. pixelIndexSlice++;
  60456. if (pixelIndexSlice % size == 0) {
  60457. pixelIndexH++;
  60458. pixelIndexSlice = 0;
  60459. if (pixelIndexH % size == 0) {
  60460. pixelIndexW++;
  60461. pixelIndexH = 0;
  60462. }
  60463. }
  60464. }
  60465. }
  60466. for (var i = 0; i < tempData.length; i++) {
  60467. var value = tempData[i];
  60468. data[i] = (value / maxColor * 255);
  60469. }
  60470. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  60471. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  60472. };
  60473. BABYLON.Tools.LoadFile(this.url, callback);
  60474. return this._texture;
  60475. };
  60476. /**
  60477. * Starts the loading process of the texture.
  60478. */
  60479. ColorGradingTexture.prototype.loadTexture = function () {
  60480. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  60481. this.load3dlTexture();
  60482. }
  60483. };
  60484. /**
  60485. * Clones the color gradind texture.
  60486. */
  60487. ColorGradingTexture.prototype.clone = function () {
  60488. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  60489. // Base texture
  60490. newTexture.level = this.level;
  60491. return newTexture;
  60492. };
  60493. /**
  60494. * Called during delayed load for textures.
  60495. */
  60496. ColorGradingTexture.prototype.delayLoad = function () {
  60497. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60498. return;
  60499. }
  60500. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  60501. this._texture = this._getFromCache(this.url, true);
  60502. if (!this._texture) {
  60503. this.loadTexture();
  60504. }
  60505. };
  60506. /**
  60507. * Binds the color grading to the shader.
  60508. * @param colorGrading The texture to bind
  60509. * @param effect The effect to bind to
  60510. */
  60511. ColorGradingTexture.Bind = function (colorGrading, effect) {
  60512. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  60513. var x = colorGrading.level; // Texture Level
  60514. var y = colorGrading.getSize().height; // Texture Size example with 8
  60515. var z = y - 1.0; // SizeMinusOne 8 - 1
  60516. var w = 1 / y; // Space of 1 slice 1 / 8
  60517. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  60518. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  60519. var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8 // Space of 1 pixel in V direction, e.g. 1/8
  60520. var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  60521. var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  60522. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  60523. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  60524. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  60525. };
  60526. /**
  60527. * Prepare the list of uniforms associated with the ColorGrading effects.
  60528. * @param uniformsList The list of uniforms used in the effect
  60529. * @param samplersList The list of samplers used in the effect
  60530. */
  60531. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  60532. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  60533. samplersList.push("cameraColorGrading2DSampler");
  60534. };
  60535. /**
  60536. * Parses a color grading texture serialized by Babylon.
  60537. * @param parsedTexture The texture information being parsedTexture
  60538. * @param scene The scene to load the texture in
  60539. * @param rootUrl The root url of the data assets to load
  60540. * @return A color gradind texture
  60541. */
  60542. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60543. var texture = null;
  60544. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  60545. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  60546. texture.name = parsedTexture.name;
  60547. texture.level = parsedTexture.level;
  60548. }
  60549. return texture;
  60550. };
  60551. /**
  60552. * Serializes the LUT texture to json format.
  60553. */
  60554. ColorGradingTexture.prototype.serialize = function () {
  60555. if (!this.name) {
  60556. return null;
  60557. }
  60558. var serializationObject = {};
  60559. serializationObject.name = this.name;
  60560. serializationObject.level = this.level;
  60561. serializationObject.customType = "BABYLON.ColorGradingTexture";
  60562. return serializationObject;
  60563. };
  60564. return ColorGradingTexture;
  60565. }(BABYLON.BaseTexture));
  60566. /**
  60567. * Empty line regex stored for GC.
  60568. */
  60569. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  60570. BABYLON.ColorGradingTexture = ColorGradingTexture;
  60571. })(BABYLON || (BABYLON = {}));
  60572. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  60573. var BABYLON;
  60574. (function (BABYLON) {
  60575. /**
  60576. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  60577. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  60578. * 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;
  60579. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  60580. */
  60581. var ColorCurves = (function () {
  60582. function ColorCurves() {
  60583. this._dirty = true;
  60584. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  60585. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  60586. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  60587. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  60588. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  60589. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  60590. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  60591. this._globalHue = 30;
  60592. this._globalDensity = 0;
  60593. this._globalSaturation = 0;
  60594. this._globalExposure = 0;
  60595. this._highlightsHue = 30;
  60596. this._highlightsDensity = 0;
  60597. this._highlightsSaturation = 0;
  60598. this._highlightsExposure = 0;
  60599. this._midtonesHue = 30;
  60600. this._midtonesDensity = 0;
  60601. this._midtonesSaturation = 0;
  60602. this._midtonesExposure = 0;
  60603. this._shadowsHue = 30;
  60604. this._shadowsDensity = 0;
  60605. this._shadowsSaturation = 0;
  60606. this._shadowsExposure = 0;
  60607. }
  60608. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  60609. /**
  60610. * Gets the global Hue value.
  60611. * 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).
  60612. */
  60613. get: function () {
  60614. return this._globalHue;
  60615. },
  60616. /**
  60617. * Sets the global Hue value.
  60618. * 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).
  60619. */
  60620. set: function (value) {
  60621. this._globalHue = value;
  60622. this._dirty = true;
  60623. },
  60624. enumerable: true,
  60625. configurable: true
  60626. });
  60627. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  60628. /**
  60629. * Gets the global Density value.
  60630. * 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.
  60631. * Values less than zero provide a filter of opposite hue.
  60632. */
  60633. get: function () {
  60634. return this._globalDensity;
  60635. },
  60636. /**
  60637. * Sets the global Density value.
  60638. * 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.
  60639. * Values less than zero provide a filter of opposite hue.
  60640. */
  60641. set: function (value) {
  60642. this._globalDensity = value;
  60643. this._dirty = true;
  60644. },
  60645. enumerable: true,
  60646. configurable: true
  60647. });
  60648. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  60649. /**
  60650. * Gets the global Saturation value.
  60651. * 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.
  60652. */
  60653. get: function () {
  60654. return this._globalSaturation;
  60655. },
  60656. /**
  60657. * Sets the global Saturation value.
  60658. * 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.
  60659. */
  60660. set: function (value) {
  60661. this._globalSaturation = value;
  60662. this._dirty = true;
  60663. },
  60664. enumerable: true,
  60665. configurable: true
  60666. });
  60667. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  60668. /**
  60669. * Gets the highlights Hue value.
  60670. * 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).
  60671. */
  60672. get: function () {
  60673. return this._highlightsHue;
  60674. },
  60675. /**
  60676. * Sets the highlights Hue value.
  60677. * 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).
  60678. */
  60679. set: function (value) {
  60680. this._highlightsHue = value;
  60681. this._dirty = true;
  60682. },
  60683. enumerable: true,
  60684. configurable: true
  60685. });
  60686. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  60687. /**
  60688. * Gets the highlights Density value.
  60689. * 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.
  60690. * Values less than zero provide a filter of opposite hue.
  60691. */
  60692. get: function () {
  60693. return this._highlightsDensity;
  60694. },
  60695. /**
  60696. * Sets the highlights Density value.
  60697. * 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.
  60698. * Values less than zero provide a filter of opposite hue.
  60699. */
  60700. set: function (value) {
  60701. this._highlightsDensity = value;
  60702. this._dirty = true;
  60703. },
  60704. enumerable: true,
  60705. configurable: true
  60706. });
  60707. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  60708. /**
  60709. * Gets the highlights Saturation value.
  60710. * 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.
  60711. */
  60712. get: function () {
  60713. return this._highlightsSaturation;
  60714. },
  60715. /**
  60716. * Sets the highlights Saturation value.
  60717. * 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.
  60718. */
  60719. set: function (value) {
  60720. this._highlightsSaturation = value;
  60721. this._dirty = true;
  60722. },
  60723. enumerable: true,
  60724. configurable: true
  60725. });
  60726. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  60727. /**
  60728. * Gets the highlights Exposure value.
  60729. * 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.
  60730. */
  60731. get: function () {
  60732. return this._highlightsExposure;
  60733. },
  60734. /**
  60735. * Sets the highlights Exposure value.
  60736. * 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.
  60737. */
  60738. set: function (value) {
  60739. this._highlightsExposure = value;
  60740. this._dirty = true;
  60741. },
  60742. enumerable: true,
  60743. configurable: true
  60744. });
  60745. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  60746. /**
  60747. * Gets the midtones Hue value.
  60748. * 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).
  60749. */
  60750. get: function () {
  60751. return this._midtonesHue;
  60752. },
  60753. /**
  60754. * Sets the midtones Hue value.
  60755. * 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).
  60756. */
  60757. set: function (value) {
  60758. this._midtonesHue = value;
  60759. this._dirty = true;
  60760. },
  60761. enumerable: true,
  60762. configurable: true
  60763. });
  60764. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  60765. /**
  60766. * Gets the midtones Density value.
  60767. * 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.
  60768. * Values less than zero provide a filter of opposite hue.
  60769. */
  60770. get: function () {
  60771. return this._midtonesDensity;
  60772. },
  60773. /**
  60774. * Sets the midtones Density value.
  60775. * 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.
  60776. * Values less than zero provide a filter of opposite hue.
  60777. */
  60778. set: function (value) {
  60779. this._midtonesDensity = value;
  60780. this._dirty = true;
  60781. },
  60782. enumerable: true,
  60783. configurable: true
  60784. });
  60785. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  60786. /**
  60787. * Gets the midtones Saturation value.
  60788. * 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.
  60789. */
  60790. get: function () {
  60791. return this._midtonesSaturation;
  60792. },
  60793. /**
  60794. * Sets the midtones Saturation value.
  60795. * 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.
  60796. */
  60797. set: function (value) {
  60798. this._midtonesSaturation = value;
  60799. this._dirty = true;
  60800. },
  60801. enumerable: true,
  60802. configurable: true
  60803. });
  60804. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  60805. /**
  60806. * Gets the midtones Exposure value.
  60807. * 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.
  60808. */
  60809. get: function () {
  60810. return this._midtonesExposure;
  60811. },
  60812. /**
  60813. * Sets the midtones Exposure value.
  60814. * 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.
  60815. */
  60816. set: function (value) {
  60817. this._midtonesExposure = value;
  60818. this._dirty = true;
  60819. },
  60820. enumerable: true,
  60821. configurable: true
  60822. });
  60823. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  60824. /**
  60825. * Gets the shadows Hue value.
  60826. * 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).
  60827. */
  60828. get: function () {
  60829. return this._shadowsHue;
  60830. },
  60831. /**
  60832. * Sets the shadows Hue value.
  60833. * 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).
  60834. */
  60835. set: function (value) {
  60836. this._shadowsHue = value;
  60837. this._dirty = true;
  60838. },
  60839. enumerable: true,
  60840. configurable: true
  60841. });
  60842. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  60843. /**
  60844. * Gets the shadows Density value.
  60845. * 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.
  60846. * Values less than zero provide a filter of opposite hue.
  60847. */
  60848. get: function () {
  60849. return this._shadowsDensity;
  60850. },
  60851. /**
  60852. * Sets the shadows Density value.
  60853. * 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.
  60854. * Values less than zero provide a filter of opposite hue.
  60855. */
  60856. set: function (value) {
  60857. this._shadowsDensity = value;
  60858. this._dirty = true;
  60859. },
  60860. enumerable: true,
  60861. configurable: true
  60862. });
  60863. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  60864. /**
  60865. * Gets the shadows Saturation value.
  60866. * 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.
  60867. */
  60868. get: function () {
  60869. return this._shadowsSaturation;
  60870. },
  60871. /**
  60872. * Sets the shadows Saturation value.
  60873. * 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.
  60874. */
  60875. set: function (value) {
  60876. this._shadowsSaturation = value;
  60877. this._dirty = true;
  60878. },
  60879. enumerable: true,
  60880. configurable: true
  60881. });
  60882. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  60883. /**
  60884. * Gets the shadows Exposure value.
  60885. * 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.
  60886. */
  60887. get: function () {
  60888. return this._shadowsExposure;
  60889. },
  60890. /**
  60891. * Sets the shadows Exposure value.
  60892. * 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.
  60893. */
  60894. set: function (value) {
  60895. this._shadowsExposure = value;
  60896. this._dirty = true;
  60897. },
  60898. enumerable: true,
  60899. configurable: true
  60900. });
  60901. /**
  60902. * Binds the color curves to the shader.
  60903. * @param colorCurves The color curve to bind
  60904. * @param effect The effect to bind to
  60905. */
  60906. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  60907. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  60908. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  60909. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  60910. if (colorCurves._dirty) {
  60911. colorCurves._dirty = false;
  60912. // Fill in global info.
  60913. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  60914. // Compute highlights info.
  60915. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  60916. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  60917. // Compute midtones info.
  60918. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  60919. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  60920. // Compute shadows info.
  60921. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  60922. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  60923. // Compute deltas (neutral is midtones).
  60924. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  60925. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  60926. }
  60927. if (effect) {
  60928. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  60929. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  60930. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  60931. }
  60932. };
  60933. /**
  60934. * Prepare the list of uniforms associated with the ColorCurves effects.
  60935. * @param uniformsList The list of uniforms used in the effect
  60936. */
  60937. ColorCurves.PrepareUniforms = function (uniformsList) {
  60938. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  60939. };
  60940. /**
  60941. * Returns color grading data based on a hue, density, saturation and exposure value.
  60942. * @param filterHue The hue of the color filter.
  60943. * @param filterDensity The density of the color filter.
  60944. * @param saturation The saturation.
  60945. * @param exposure The exposure.
  60946. * @param result The result data container.
  60947. */
  60948. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  60949. if (hue == null) {
  60950. return;
  60951. }
  60952. hue = ColorCurves.clamp(hue, 0, 360);
  60953. density = ColorCurves.clamp(density, -100, 100);
  60954. saturation = ColorCurves.clamp(saturation, -100, 100);
  60955. exposure = ColorCurves.clamp(exposure, -100, 100);
  60956. // Remap the slider/config filter density with non-linear mapping and also scale by half
  60957. // so that the maximum filter density is only 50% control. This provides fine control
  60958. // for small values and reasonable range.
  60959. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  60960. density *= 0.5;
  60961. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  60962. if (density < 0) {
  60963. density *= -1;
  60964. hue = (hue + 180) % 360;
  60965. }
  60966. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  60967. result.scaleToRef(2, result);
  60968. result.a = 1 + 0.01 * saturation;
  60969. };
  60970. /**
  60971. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  60972. * @param value The input slider value in range [-100,100].
  60973. * @returns Adjusted value.
  60974. */
  60975. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  60976. value /= 100;
  60977. var x = Math.abs(value);
  60978. x = Math.pow(x, 2);
  60979. if (value < 0) {
  60980. x *= -1;
  60981. }
  60982. x *= 100;
  60983. return x;
  60984. };
  60985. /**
  60986. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  60987. * @param hue The hue (H) input.
  60988. * @param saturation The saturation (S) input.
  60989. * @param brightness The brightness (B) input.
  60990. * @result An RGBA color represented as Vector4.
  60991. */
  60992. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  60993. var h = ColorCurves.clamp(hue, 0, 360);
  60994. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  60995. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  60996. if (s === 0) {
  60997. result.r = v;
  60998. result.g = v;
  60999. result.b = v;
  61000. }
  61001. else {
  61002. // sector 0 to 5
  61003. h /= 60;
  61004. var i = Math.floor(h);
  61005. // fractional part of h
  61006. var f = h - i;
  61007. var p = v * (1 - s);
  61008. var q = v * (1 - s * f);
  61009. var t = v * (1 - s * (1 - f));
  61010. switch (i) {
  61011. case 0:
  61012. result.r = v;
  61013. result.g = t;
  61014. result.b = p;
  61015. break;
  61016. case 1:
  61017. result.r = q;
  61018. result.g = v;
  61019. result.b = p;
  61020. break;
  61021. case 2:
  61022. result.r = p;
  61023. result.g = v;
  61024. result.b = t;
  61025. break;
  61026. case 3:
  61027. result.r = p;
  61028. result.g = q;
  61029. result.b = v;
  61030. break;
  61031. case 4:
  61032. result.r = t;
  61033. result.g = p;
  61034. result.b = v;
  61035. break;
  61036. default:
  61037. result.r = v;
  61038. result.g = p;
  61039. result.b = q;
  61040. break;
  61041. }
  61042. }
  61043. result.a = 1;
  61044. };
  61045. /**
  61046. * Returns a value clamped between min and max
  61047. * @param value The value to clamp
  61048. * @param min The minimum of value
  61049. * @param max The maximum of value
  61050. * @returns The clamped value.
  61051. */
  61052. ColorCurves.clamp = function (value, min, max) {
  61053. return Math.min(Math.max(value, min), max);
  61054. };
  61055. /**
  61056. * Clones the current color curve instance.
  61057. * @return The cloned curves
  61058. */
  61059. ColorCurves.prototype.clone = function () {
  61060. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  61061. };
  61062. /**
  61063. * Serializes the current color curve instance to a json representation.
  61064. * @return a JSON representation
  61065. */
  61066. ColorCurves.prototype.serialize = function () {
  61067. return BABYLON.SerializationHelper.Serialize(this);
  61068. };
  61069. /**
  61070. * Parses the color curve from a json representation.
  61071. * @param source the JSON source to parse
  61072. * @return The parsed curves
  61073. */
  61074. ColorCurves.Parse = function (source) {
  61075. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  61076. };
  61077. return ColorCurves;
  61078. }());
  61079. __decorate([
  61080. BABYLON.serialize()
  61081. ], ColorCurves.prototype, "_globalHue", void 0);
  61082. __decorate([
  61083. BABYLON.serialize()
  61084. ], ColorCurves.prototype, "_globalDensity", void 0);
  61085. __decorate([
  61086. BABYLON.serialize()
  61087. ], ColorCurves.prototype, "_globalSaturation", void 0);
  61088. __decorate([
  61089. BABYLON.serialize()
  61090. ], ColorCurves.prototype, "_globalExposure", void 0);
  61091. __decorate([
  61092. BABYLON.serialize()
  61093. ], ColorCurves.prototype, "_highlightsHue", void 0);
  61094. __decorate([
  61095. BABYLON.serialize()
  61096. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  61097. __decorate([
  61098. BABYLON.serialize()
  61099. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  61100. __decorate([
  61101. BABYLON.serialize()
  61102. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  61103. __decorate([
  61104. BABYLON.serialize()
  61105. ], ColorCurves.prototype, "_midtonesHue", void 0);
  61106. __decorate([
  61107. BABYLON.serialize()
  61108. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  61109. __decorate([
  61110. BABYLON.serialize()
  61111. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  61112. __decorate([
  61113. BABYLON.serialize()
  61114. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  61115. BABYLON.ColorCurves = ColorCurves;
  61116. })(BABYLON || (BABYLON = {}));
  61117. //# sourceMappingURL=babylon.colorCurves.js.map
  61118. var BABYLON;
  61119. (function (BABYLON) {
  61120. var Octree = (function () {
  61121. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  61122. if (maxDepth === void 0) { maxDepth = 2; }
  61123. this.maxDepth = maxDepth;
  61124. this.dynamicContent = new Array();
  61125. this._maxBlockCapacity = maxBlockCapacity || 64;
  61126. this._selectionContent = new BABYLON.SmartArray(1024);
  61127. this._creationFunc = creationFunc;
  61128. }
  61129. // Methods
  61130. Octree.prototype.update = function (worldMin, worldMax, entries) {
  61131. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  61132. };
  61133. Octree.prototype.addMesh = function (entry) {
  61134. for (var index = 0; index < this.blocks.length; index++) {
  61135. var block = this.blocks[index];
  61136. block.addEntry(entry);
  61137. }
  61138. };
  61139. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  61140. this._selectionContent.reset();
  61141. for (var index = 0; index < this.blocks.length; index++) {
  61142. var block = this.blocks[index];
  61143. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  61144. }
  61145. if (allowDuplicate) {
  61146. this._selectionContent.concat(this.dynamicContent);
  61147. }
  61148. else {
  61149. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  61150. }
  61151. return this._selectionContent;
  61152. };
  61153. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  61154. this._selectionContent.reset();
  61155. for (var index = 0; index < this.blocks.length; index++) {
  61156. var block = this.blocks[index];
  61157. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  61158. }
  61159. if (allowDuplicate) {
  61160. this._selectionContent.concat(this.dynamicContent);
  61161. }
  61162. else {
  61163. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  61164. }
  61165. return this._selectionContent;
  61166. };
  61167. Octree.prototype.intersectsRay = function (ray) {
  61168. this._selectionContent.reset();
  61169. for (var index = 0; index < this.blocks.length; index++) {
  61170. var block = this.blocks[index];
  61171. block.intersectsRay(ray, this._selectionContent);
  61172. }
  61173. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  61174. return this._selectionContent;
  61175. };
  61176. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  61177. target.blocks = new Array();
  61178. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  61179. // Segmenting space
  61180. for (var x = 0; x < 2; x++) {
  61181. for (var y = 0; y < 2; y++) {
  61182. for (var z = 0; z < 2; z++) {
  61183. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  61184. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  61185. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  61186. block.addEntries(entries);
  61187. target.blocks.push(block);
  61188. }
  61189. }
  61190. }
  61191. };
  61192. return Octree;
  61193. }());
  61194. Octree.CreationFuncForMeshes = function (entry, block) {
  61195. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  61196. block.entries.push(entry);
  61197. }
  61198. };
  61199. Octree.CreationFuncForSubMeshes = function (entry, block) {
  61200. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  61201. block.entries.push(entry);
  61202. }
  61203. };
  61204. BABYLON.Octree = Octree;
  61205. })(BABYLON || (BABYLON = {}));
  61206. //# sourceMappingURL=babylon.octree.js.map
  61207. var BABYLON;
  61208. (function (BABYLON) {
  61209. var OctreeBlock = (function () {
  61210. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  61211. this.entries = new Array();
  61212. this._boundingVectors = new Array();
  61213. this._capacity = capacity;
  61214. this._depth = depth;
  61215. this._maxDepth = maxDepth;
  61216. this._creationFunc = creationFunc;
  61217. this._minPoint = minPoint;
  61218. this._maxPoint = maxPoint;
  61219. this._boundingVectors.push(minPoint.clone());
  61220. this._boundingVectors.push(maxPoint.clone());
  61221. this._boundingVectors.push(minPoint.clone());
  61222. this._boundingVectors[2].x = maxPoint.x;
  61223. this._boundingVectors.push(minPoint.clone());
  61224. this._boundingVectors[3].y = maxPoint.y;
  61225. this._boundingVectors.push(minPoint.clone());
  61226. this._boundingVectors[4].z = maxPoint.z;
  61227. this._boundingVectors.push(maxPoint.clone());
  61228. this._boundingVectors[5].z = minPoint.z;
  61229. this._boundingVectors.push(maxPoint.clone());
  61230. this._boundingVectors[6].x = minPoint.x;
  61231. this._boundingVectors.push(maxPoint.clone());
  61232. this._boundingVectors[7].y = minPoint.y;
  61233. }
  61234. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  61235. // Property
  61236. get: function () {
  61237. return this._capacity;
  61238. },
  61239. enumerable: true,
  61240. configurable: true
  61241. });
  61242. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  61243. get: function () {
  61244. return this._minPoint;
  61245. },
  61246. enumerable: true,
  61247. configurable: true
  61248. });
  61249. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  61250. get: function () {
  61251. return this._maxPoint;
  61252. },
  61253. enumerable: true,
  61254. configurable: true
  61255. });
  61256. // Methods
  61257. OctreeBlock.prototype.addEntry = function (entry) {
  61258. if (this.blocks) {
  61259. for (var index = 0; index < this.blocks.length; index++) {
  61260. var block = this.blocks[index];
  61261. block.addEntry(entry);
  61262. }
  61263. return;
  61264. }
  61265. this._creationFunc(entry, this);
  61266. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  61267. this.createInnerBlocks();
  61268. }
  61269. };
  61270. OctreeBlock.prototype.addEntries = function (entries) {
  61271. for (var index = 0; index < entries.length; index++) {
  61272. var mesh = entries[index];
  61273. this.addEntry(mesh);
  61274. }
  61275. };
  61276. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  61277. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  61278. if (this.blocks) {
  61279. for (var index = 0; index < this.blocks.length; index++) {
  61280. var block = this.blocks[index];
  61281. block.select(frustumPlanes, selection, allowDuplicate);
  61282. }
  61283. return;
  61284. }
  61285. if (allowDuplicate) {
  61286. selection.concat(this.entries);
  61287. }
  61288. else {
  61289. selection.concatWithNoDuplicate(this.entries);
  61290. }
  61291. }
  61292. };
  61293. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  61294. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  61295. if (this.blocks) {
  61296. for (var index = 0; index < this.blocks.length; index++) {
  61297. var block = this.blocks[index];
  61298. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  61299. }
  61300. return;
  61301. }
  61302. if (allowDuplicate) {
  61303. selection.concat(this.entries);
  61304. }
  61305. else {
  61306. selection.concatWithNoDuplicate(this.entries);
  61307. }
  61308. }
  61309. };
  61310. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  61311. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  61312. if (this.blocks) {
  61313. for (var index = 0; index < this.blocks.length; index++) {
  61314. var block = this.blocks[index];
  61315. block.intersectsRay(ray, selection);
  61316. }
  61317. return;
  61318. }
  61319. selection.concatWithNoDuplicate(this.entries);
  61320. }
  61321. };
  61322. OctreeBlock.prototype.createInnerBlocks = function () {
  61323. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  61324. };
  61325. return OctreeBlock;
  61326. }());
  61327. BABYLON.OctreeBlock = OctreeBlock;
  61328. })(BABYLON || (BABYLON = {}));
  61329. //# sourceMappingURL=babylon.octreeBlock.js.map
  61330. var BABYLON;
  61331. (function (BABYLON) {
  61332. var SIMDVector3 = (function () {
  61333. function SIMDVector3() {
  61334. }
  61335. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  61336. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  61337. };
  61338. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  61339. var m = transformation.m;
  61340. var m0 = SIMD.Float32x4.load(m, 0);
  61341. var m1 = SIMD.Float32x4.load(m, 4);
  61342. var m2 = SIMD.Float32x4.load(m, 8);
  61343. var m3 = SIMD.Float32x4.load(m, 12);
  61344. 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));
  61345. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  61346. result.x = SIMD.Float32x4.extractLane(r, 0);
  61347. result.y = SIMD.Float32x4.extractLane(r, 1);
  61348. result.z = SIMD.Float32x4.extractLane(r, 2);
  61349. };
  61350. return SIMDVector3;
  61351. }());
  61352. var SIMDMatrix = (function () {
  61353. function SIMDMatrix() {
  61354. }
  61355. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  61356. var tm = this.m;
  61357. var om = other.m;
  61358. var m0 = SIMD.Float32x4.load(om, 0);
  61359. var m1 = SIMD.Float32x4.load(om, 4);
  61360. var m2 = SIMD.Float32x4.load(om, 8);
  61361. var m3 = SIMD.Float32x4.load(om, 12);
  61362. for (var i = 0; i < 16; i += 4) {
  61363. 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)))));
  61364. }
  61365. return this;
  61366. };
  61367. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  61368. var src = this.m;
  61369. var dest = other.m;
  61370. // Load the 4 rows
  61371. var src0 = SIMD.Float32x4.load(src, 0);
  61372. var src1 = SIMD.Float32x4.load(src, 4);
  61373. var src2 = SIMD.Float32x4.load(src, 8);
  61374. var src3 = SIMD.Float32x4.load(src, 12);
  61375. // Transpose the source matrix. Sort of. Not a true transpose operation
  61376. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  61377. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  61378. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  61379. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  61380. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  61381. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  61382. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  61383. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  61384. // This is a true transposition, but it will lead to an incorrect result
  61385. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  61386. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  61387. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  61388. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  61389. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  61390. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  61391. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  61392. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  61393. // ----
  61394. tmp1 = SIMD.Float32x4.mul(row2, row3);
  61395. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  61396. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  61397. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  61398. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  61399. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  61400. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  61401. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  61402. // ----
  61403. tmp1 = SIMD.Float32x4.mul(row1, row2);
  61404. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  61405. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  61406. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  61407. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  61408. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  61409. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  61410. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  61411. // ----
  61412. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  61413. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  61414. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  61415. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  61416. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  61417. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  61418. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  61419. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  61420. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  61421. // ----
  61422. tmp1 = SIMD.Float32x4.mul(row0, row1);
  61423. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  61424. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  61425. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  61426. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  61427. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  61428. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  61429. // ----
  61430. tmp1 = SIMD.Float32x4.mul(row0, row3);
  61431. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  61432. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  61433. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  61434. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  61435. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  61436. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  61437. // ----
  61438. tmp1 = SIMD.Float32x4.mul(row0, row2);
  61439. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  61440. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  61441. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  61442. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  61443. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  61444. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  61445. // Compute determinant
  61446. var det = SIMD.Float32x4.mul(row0, minor0);
  61447. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  61448. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  61449. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  61450. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  61451. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  61452. // These shuffles aren't necessary if the faulty transposition is done
  61453. // up at the top of this function.
  61454. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  61455. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  61456. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  61457. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  61458. // Compute final values by multiplying with 1/det
  61459. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  61460. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  61461. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  61462. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  61463. return this;
  61464. };
  61465. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  61466. var out = result.m;
  61467. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  61468. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  61469. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  61470. // cc.kmVec3Subtract(f, pCenter, pEye);
  61471. var f = SIMD.Float32x4.sub(center, eye);
  61472. // cc.kmVec3Normalize(f, f);
  61473. var tmp = SIMD.Float32x4.mul(f, f);
  61474. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  61475. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  61476. // cc.kmVec3Assign(up, pUp);
  61477. // cc.kmVec3Normalize(up, up);
  61478. tmp = SIMD.Float32x4.mul(up, up);
  61479. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  61480. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  61481. // cc.kmVec3Cross(s, f, up);
  61482. 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)));
  61483. // cc.kmVec3Normalize(s, s);
  61484. tmp = SIMD.Float32x4.mul(s, s);
  61485. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  61486. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  61487. // cc.kmVec3Cross(u, s, f);
  61488. 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)));
  61489. // cc.kmVec3Normalize(s, s);
  61490. tmp = SIMD.Float32x4.mul(s, s);
  61491. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  61492. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  61493. var zero = SIMD.Float32x4.splat(0.0);
  61494. s = SIMD.Float32x4.neg(s);
  61495. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  61496. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  61497. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  61498. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  61499. 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);
  61500. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  61501. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  61502. 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)))));
  61503. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  61504. 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)))));
  61505. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  61506. 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)))));
  61507. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  61508. 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)))));
  61509. };
  61510. return SIMDMatrix;
  61511. }());
  61512. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  61513. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  61514. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  61515. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  61516. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  61517. var SIMDHelper = (function () {
  61518. function SIMDHelper() {
  61519. }
  61520. Object.defineProperty(SIMDHelper, "IsEnabled", {
  61521. get: function () {
  61522. return SIMDHelper._isEnabled;
  61523. },
  61524. enumerable: true,
  61525. configurable: true
  61526. });
  61527. SIMDHelper.DisableSIMD = function () {
  61528. // Replace functions
  61529. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  61530. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  61531. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  61532. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  61533. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  61534. SIMDHelper._isEnabled = false;
  61535. };
  61536. SIMDHelper.EnableSIMD = function () {
  61537. if (self.SIMD === undefined) {
  61538. return;
  61539. }
  61540. // check if polyfills needed
  61541. if (!self.Math.fround) {
  61542. self.Math.fround = (function (array) { return function (x) {
  61543. return array[0] = x, array[0];
  61544. }; })(new Float32Array(1));
  61545. }
  61546. if (!self.Math.imul) {
  61547. self.Math.imul = function (a, b) {
  61548. var ah = (a >>> 16) & 0xffff;
  61549. var al = a & 0xffff;
  61550. var bh = (b >>> 16) & 0xffff;
  61551. var bl = b & 0xffff;
  61552. // the shift by 0 fixes the sign on the high part
  61553. // the final |0 converts the unsigned value into a signed value
  61554. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  61555. };
  61556. }
  61557. // Replace functions
  61558. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  61559. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  61560. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  61561. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  61562. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  61563. SIMDHelper._isEnabled = true;
  61564. };
  61565. return SIMDHelper;
  61566. }());
  61567. SIMDHelper._isEnabled = false;
  61568. BABYLON.SIMDHelper = SIMDHelper;
  61569. })(BABYLON || (BABYLON = {}));
  61570. //# sourceMappingURL=babylon.math.SIMD.js.map
  61571. var BABYLON;
  61572. (function (BABYLON) {
  61573. var VRDistortionCorrectionPostProcess = (function (_super) {
  61574. __extends(VRDistortionCorrectionPostProcess, _super);
  61575. //ANY
  61576. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  61577. var _this = _super.call(this, name, "vrDistortionCorrection", [
  61578. 'LensCenter',
  61579. 'Scale',
  61580. 'ScaleIn',
  61581. 'HmdWarpParam'
  61582. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  61583. _this._isRightEye = isRightEye;
  61584. _this._distortionFactors = vrMetrics.distortionK;
  61585. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  61586. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  61587. _this.onSizeChangedObservable.add(function () {
  61588. _this.aspectRatio = _this.width * .5 / _this.height;
  61589. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  61590. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  61591. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  61592. });
  61593. _this.onApplyObservable.add(function (effect) {
  61594. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  61595. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  61596. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  61597. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  61598. });
  61599. return _this;
  61600. }
  61601. return VRDistortionCorrectionPostProcess;
  61602. }(BABYLON.PostProcess));
  61603. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  61604. })(BABYLON || (BABYLON = {}));
  61605. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  61606. var BABYLON;
  61607. (function (BABYLON) {
  61608. var AnaglyphPostProcess = (function (_super) {
  61609. __extends(AnaglyphPostProcess, _super);
  61610. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  61611. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  61612. _this._passedProcess = rigCameras[0]._rigPostProcess;
  61613. _this.onApplyObservable.add(function (effect) {
  61614. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  61615. });
  61616. return _this;
  61617. }
  61618. return AnaglyphPostProcess;
  61619. }(BABYLON.PostProcess));
  61620. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  61621. })(BABYLON || (BABYLON = {}));
  61622. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  61623. var BABYLON;
  61624. (function (BABYLON) {
  61625. var StereoscopicInterlacePostProcess = (function (_super) {
  61626. __extends(StereoscopicInterlacePostProcess, _super);
  61627. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  61628. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  61629. _this._passedProcess = rigCameras[0]._rigPostProcess;
  61630. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  61631. _this.onSizeChangedObservable.add(function () {
  61632. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  61633. });
  61634. _this.onApplyObservable.add(function (effect) {
  61635. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  61636. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  61637. });
  61638. return _this;
  61639. }
  61640. return StereoscopicInterlacePostProcess;
  61641. }(BABYLON.PostProcess));
  61642. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  61643. })(BABYLON || (BABYLON = {}));
  61644. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  61645. var BABYLON;
  61646. (function (BABYLON) {
  61647. var FreeCameraDeviceOrientationInput = (function () {
  61648. function FreeCameraDeviceOrientationInput() {
  61649. var _this = this;
  61650. this._screenOrientationAngle = 0;
  61651. this._screenQuaternion = new BABYLON.Quaternion();
  61652. this._alpha = 0;
  61653. this._beta = 0;
  61654. this._gamma = 0;
  61655. this._orientationChanged = function () {
  61656. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  61657. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  61658. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  61659. };
  61660. this._deviceOrientation = function (evt) {
  61661. _this._alpha = evt.alpha;
  61662. _this._beta = evt.beta;
  61663. _this._gamma = evt.gamma;
  61664. };
  61665. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  61666. this._orientationChanged();
  61667. }
  61668. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  61669. get: function () {
  61670. return this._camera;
  61671. },
  61672. set: function (camera) {
  61673. this._camera = camera;
  61674. if (!this._camera.rotationQuaternion)
  61675. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  61676. },
  61677. enumerable: true,
  61678. configurable: true
  61679. });
  61680. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  61681. window.addEventListener("orientationchange", this._orientationChanged);
  61682. window.addEventListener("deviceorientation", this._deviceOrientation);
  61683. //In certain cases, the attach control is called AFTER orientation was changed,
  61684. //So this is needed.
  61685. this._orientationChanged();
  61686. };
  61687. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  61688. window.removeEventListener("orientationchange", this._orientationChanged);
  61689. window.removeEventListener("deviceorientation", this._deviceOrientation);
  61690. };
  61691. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  61692. //if no device orientation provided, don't update the rotation.
  61693. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  61694. if (!this._alpha)
  61695. return;
  61696. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  61697. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  61698. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  61699. //Mirror on XY Plane
  61700. this._camera.rotationQuaternion.z *= -1;
  61701. this._camera.rotationQuaternion.w *= -1;
  61702. };
  61703. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  61704. return "FreeCameraDeviceOrientationInput";
  61705. };
  61706. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  61707. return "deviceOrientation";
  61708. };
  61709. return FreeCameraDeviceOrientationInput;
  61710. }());
  61711. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  61712. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  61713. })(BABYLON || (BABYLON = {}));
  61714. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  61715. var BABYLON;
  61716. (function (BABYLON) {
  61717. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  61718. function ArcRotateCameraVRDeviceOrientationInput() {
  61719. this.alphaCorrection = 1;
  61720. this.betaCorrection = 1;
  61721. this.gammaCorrection = 1;
  61722. this._alpha = 0;
  61723. this._beta = 0;
  61724. this._gamma = 0;
  61725. this._dirty = false;
  61726. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  61727. }
  61728. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  61729. this.camera.attachControl(element, noPreventDefault);
  61730. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  61731. };
  61732. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  61733. var camera = this.camera;
  61734. this._alpha = +evt.alpha | 0;
  61735. this._beta = +evt.beta | 0;
  61736. this._gamma = +evt.gamma | 0;
  61737. this._dirty = true;
  61738. };
  61739. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  61740. if (this._dirty) {
  61741. this._dirty = false;
  61742. if (this._gamma < 0) {
  61743. this._gamma = 180 + this._gamma;
  61744. }
  61745. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  61746. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  61747. }
  61748. };
  61749. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  61750. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  61751. };
  61752. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  61753. return "ArcRotateCameraVRDeviceOrientationInput";
  61754. };
  61755. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  61756. return "VRDeviceOrientation";
  61757. };
  61758. return ArcRotateCameraVRDeviceOrientationInput;
  61759. }());
  61760. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  61761. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  61762. })(BABYLON || (BABYLON = {}));
  61763. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  61764. var BABYLON;
  61765. (function (BABYLON) {
  61766. var VRCameraMetrics = (function () {
  61767. function VRCameraMetrics() {
  61768. this.compensateDistortion = true;
  61769. }
  61770. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  61771. get: function () {
  61772. return this.hResolution / (2 * this.vResolution);
  61773. },
  61774. enumerable: true,
  61775. configurable: true
  61776. });
  61777. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  61778. get: function () {
  61779. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  61780. },
  61781. enumerable: true,
  61782. configurable: true
  61783. });
  61784. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  61785. get: function () {
  61786. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  61787. var h = (4 * meters) / this.hScreenSize;
  61788. return BABYLON.Matrix.Translation(h, 0, 0);
  61789. },
  61790. enumerable: true,
  61791. configurable: true
  61792. });
  61793. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  61794. get: function () {
  61795. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  61796. var h = (4 * meters) / this.hScreenSize;
  61797. return BABYLON.Matrix.Translation(-h, 0, 0);
  61798. },
  61799. enumerable: true,
  61800. configurable: true
  61801. });
  61802. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  61803. get: function () {
  61804. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  61805. },
  61806. enumerable: true,
  61807. configurable: true
  61808. });
  61809. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  61810. get: function () {
  61811. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  61812. },
  61813. enumerable: true,
  61814. configurable: true
  61815. });
  61816. VRCameraMetrics.GetDefault = function () {
  61817. var result = new VRCameraMetrics();
  61818. result.hResolution = 1280;
  61819. result.vResolution = 800;
  61820. result.hScreenSize = 0.149759993;
  61821. result.vScreenSize = 0.0935999975;
  61822. result.vScreenCenter = 0.0467999987;
  61823. result.eyeToScreenDistance = 0.0410000011;
  61824. result.lensSeparationDistance = 0.0635000020;
  61825. result.interpupillaryDistance = 0.0640000030;
  61826. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  61827. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  61828. result.postProcessScaleFactor = 1.714605507808412;
  61829. result.lensCenterOffset = 0.151976421;
  61830. return result;
  61831. };
  61832. return VRCameraMetrics;
  61833. }());
  61834. BABYLON.VRCameraMetrics = VRCameraMetrics;
  61835. })(BABYLON || (BABYLON = {}));
  61836. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  61837. var BABYLON;
  61838. (function (BABYLON) {
  61839. var WebVRFreeCamera = (function (_super) {
  61840. __extends(WebVRFreeCamera, _super);
  61841. function WebVRFreeCamera(name, position, scene, webVROptions) {
  61842. if (webVROptions === void 0) { webVROptions = {}; }
  61843. var _this = _super.call(this, name, position, scene) || this;
  61844. _this.webVROptions = webVROptions;
  61845. _this._vrDevice = null;
  61846. _this.rawPose = null;
  61847. _this._vrEnabled = false;
  61848. _this._specsVersion = 1.1;
  61849. _this._attached = false;
  61850. _this._positionOffset = BABYLON.Vector3.Zero();
  61851. _this._descendants = [];
  61852. _this.devicePosition = BABYLON.Vector3.Zero();
  61853. _this.deviceScaleFactor = 1;
  61854. _this.controllers = [];
  61855. _this.nonVRControllers = [];
  61856. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  61857. //legacy support - the compensation boolean was removed.
  61858. if (arguments.length === 5) {
  61859. _this.webVROptions = arguments[4];
  61860. }
  61861. // default webVR options
  61862. if (_this.webVROptions.trackPosition == undefined) {
  61863. _this.webVROptions.trackPosition = true;
  61864. }
  61865. if (_this.webVROptions.controllerMeshes == undefined) {
  61866. _this.webVROptions.controllerMeshes = true;
  61867. }
  61868. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  61869. _this.webVROptions.defaultLightningOnControllers = true;
  61870. }
  61871. _this.rotationQuaternion = new BABYLON.Quaternion();
  61872. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  61873. if (_this.webVROptions && _this.webVROptions.positionScale) {
  61874. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  61875. }
  61876. //enable VR
  61877. _this.getEngine().initWebVR();
  61878. //check specs version
  61879. if (!window.VRFrameData) {
  61880. _this._specsVersion = 1.0;
  61881. _this._frameData = {};
  61882. }
  61883. else {
  61884. _this._frameData = new VRFrameData();
  61885. }
  61886. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  61887. if (!device) {
  61888. return;
  61889. }
  61890. _this._vrEnabled = true;
  61891. _this._vrDevice = device;
  61892. //reset the rig parameters.
  61893. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  61894. if (_this._attached) {
  61895. _this.getEngine().enableVR(_this._vrDevice);
  61896. }
  61897. });
  61898. // try to attach the controllers, if found.
  61899. _this.initControllers();
  61900. /**
  61901. * The idea behind the following lines:
  61902. * objects that have the camera as parent should actually have the rig cameras as a parent.
  61903. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  61904. * the second will not show it correctly.
  61905. *
  61906. * To solve this - each object that has the camera as parent will be added to a protected array.
  61907. * When the rig camera renders, it will take this array and set all of those to be its children.
  61908. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  61909. * Amazing!
  61910. */
  61911. scene.onBeforeCameraRenderObservable.add(function (camera) {
  61912. if (camera.parent === _this && _this.rigParenting) {
  61913. _this._descendants = _this.getDescendants(true, function (n) {
  61914. // don't take the cameras or the controllers!
  61915. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  61916. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  61917. return !isController && !isRigCamera;
  61918. });
  61919. _this._descendants.forEach(function (node) {
  61920. node.parent = camera;
  61921. });
  61922. }
  61923. });
  61924. scene.onAfterCameraRenderObservable.add(function (camera) {
  61925. if (camera.parent === _this && _this.rigParenting) {
  61926. _this._descendants.forEach(function (node) {
  61927. node.parent = _this;
  61928. });
  61929. }
  61930. });
  61931. return _this;
  61932. }
  61933. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  61934. set: function (callback) {
  61935. this._onControllersAttached = callback;
  61936. // after setting - if the controllers are already set, execute the callback.
  61937. if (this.controllers.length >= 2) {
  61938. callback(this.controllers);
  61939. }
  61940. },
  61941. enumerable: true,
  61942. configurable: true
  61943. });
  61944. Object.defineProperty(WebVRFreeCamera.prototype, "onNonVRControllerAttached", {
  61945. set: function (callback) {
  61946. this._onNonVRControllerAttached = callback;
  61947. this.nonVRControllers.forEach(function (controller) {
  61948. callback(controller);
  61949. });
  61950. },
  61951. enumerable: true,
  61952. configurable: true
  61953. });
  61954. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  61955. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  61956. var gp = _a[_i];
  61957. if (gp.hand === name) {
  61958. return gp;
  61959. }
  61960. }
  61961. return undefined;
  61962. };
  61963. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  61964. get: function () {
  61965. if (!this._leftController) {
  61966. this._leftController = this.getControllerByName("left");
  61967. }
  61968. return this._leftController;
  61969. },
  61970. enumerable: true,
  61971. configurable: true
  61972. });
  61973. ;
  61974. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  61975. get: function () {
  61976. if (!this._rightController) {
  61977. this._rightController = this.getControllerByName("right");
  61978. }
  61979. return this._rightController;
  61980. },
  61981. enumerable: true,
  61982. configurable: true
  61983. });
  61984. ;
  61985. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  61986. if (length === void 0) { length = 100; }
  61987. if (this.leftCamera) {
  61988. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  61989. }
  61990. else {
  61991. return _super.prototype.getForwardRay.call(this, length);
  61992. }
  61993. };
  61994. WebVRFreeCamera.prototype._checkInputs = function () {
  61995. if (this._vrEnabled) {
  61996. if (this._specsVersion === 1.1) {
  61997. this._vrDevice.getFrameData(this._frameData);
  61998. }
  61999. else {
  62000. //backwards comp
  62001. var pose = this._vrDevice.getPose();
  62002. this._frameData.pose = pose;
  62003. // calculate view and projection matrix
  62004. }
  62005. this.updateFromDevice(this._frameData.pose);
  62006. }
  62007. _super.prototype._checkInputs.call(this);
  62008. };
  62009. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  62010. if (poseData && poseData.orientation) {
  62011. this.rawPose = poseData;
  62012. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  62013. if (this.getScene().useRightHandedSystem) {
  62014. this.deviceRotationQuaternion.z *= -1;
  62015. this.deviceRotationQuaternion.w *= -1;
  62016. }
  62017. if (this.webVROptions.trackPosition && this.rawPose.position) {
  62018. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  62019. if (this.getScene().useRightHandedSystem) {
  62020. this.devicePosition.z *= -1;
  62021. }
  62022. }
  62023. }
  62024. };
  62025. /**
  62026. * WebVR's attach control will start broadcasting frames to the device.
  62027. * Note that in certain browsers (chrome for example) this function must be called
  62028. * within a user-interaction callback. Example:
  62029. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  62030. *
  62031. * @param {HTMLElement} element
  62032. * @param {boolean} [noPreventDefault]
  62033. *
  62034. * @memberOf WebVRFreeCamera
  62035. */
  62036. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  62037. _super.prototype.attachControl.call(this, element, noPreventDefault);
  62038. this._attached = true;
  62039. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  62040. if (this._vrEnabled) {
  62041. this.getEngine().enableVR(this._vrDevice);
  62042. }
  62043. };
  62044. WebVRFreeCamera.prototype.detachControl = function (element) {
  62045. _super.prototype.detachControl.call(this, element);
  62046. this._vrEnabled = false;
  62047. this._attached = false;
  62048. this.getEngine().disableVR();
  62049. };
  62050. WebVRFreeCamera.prototype.getClassName = function () {
  62051. return "WebVRFreeCamera";
  62052. };
  62053. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  62054. //uses the vrDisplay's "resetPose()".
  62055. //pitch and roll won't be affected.
  62056. this._vrDevice.resetPose();
  62057. };
  62058. WebVRFreeCamera.prototype._updateRigCameras = function () {
  62059. var camLeft = this._rigCameras[0];
  62060. var camRight = this._rigCameras[1];
  62061. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  62062. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  62063. camLeft.position.copyFrom(this.devicePosition);
  62064. camRight.position.copyFrom(this.devicePosition);
  62065. };
  62066. /**
  62067. * This function is called by the two RIG cameras.
  62068. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  62069. */
  62070. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  62071. var _this = this;
  62072. //WebVR 1.0
  62073. if (this._cameraRigParams["specs"] === 1.0) {
  62074. this._updateCameraRotationMatrix();
  62075. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  62076. // Computing target and final matrix
  62077. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  62078. if (this.getScene().useRightHandedSystem) {
  62079. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  62080. }
  62081. else {
  62082. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  62083. }
  62084. //now move the eye in the right direction
  62085. var eyeParams = this._cameraRigParams["eyeParameters"];
  62086. var offset = eyeParams.offset;
  62087. // it will actually always be 0, but just in case
  62088. if (this.getScene().useRightHandedSystem) {
  62089. offset[2] *= -1;
  62090. }
  62091. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  62092. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  62093. }
  62094. else {
  62095. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  62096. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  62097. if (!this.getScene().useRightHandedSystem) {
  62098. [2, 6, 8, 9, 14].forEach(function (num) {
  62099. _this._webvrViewMatrix.m[num] *= -1;
  62100. });
  62101. }
  62102. // update the camera rotation matrix
  62103. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  62104. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  62105. // Computing target and final matrix
  62106. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  62107. }
  62108. var parentCamera = this._cameraRigParams["parentCamera"];
  62109. // should the view matrix be updated with scale and position offset?
  62110. if (parentCamera.deviceScaleFactor !== 1) {
  62111. this._webvrViewMatrix.invert();
  62112. // scale the position, if set
  62113. if (parentCamera.deviceScaleFactor) {
  62114. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  62115. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  62116. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  62117. }
  62118. this._webvrViewMatrix.invert();
  62119. }
  62120. return this._webvrViewMatrix;
  62121. };
  62122. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  62123. var _this = this;
  62124. if (this._cameraRigParams["specs"] === 1.0) {
  62125. var eyeParams = this._cameraRigParams["eyeParameters"];
  62126. // deprecated!!
  62127. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  62128. }
  62129. else {
  62130. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  62131. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  62132. //babylon compatible matrix
  62133. if (!this.getScene().useRightHandedSystem) {
  62134. [8, 9, 10, 11].forEach(function (num) {
  62135. _this._projectionMatrix.m[num] *= -1;
  62136. });
  62137. }
  62138. }
  62139. return this._projectionMatrix;
  62140. };
  62141. WebVRFreeCamera.prototype.initControllers = function () {
  62142. var _this = this;
  62143. this.controllers = [];
  62144. new BABYLON.Gamepads(function (gp) {
  62145. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  62146. var webVrController = gp;
  62147. if (_this.webVROptions.controllerMeshes) {
  62148. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  62149. if (_this.webVROptions.defaultLightningOnControllers) {
  62150. if (!_this._lightOnControllers) {
  62151. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  62152. }
  62153. loadedMesh.getChildren().forEach(function (mesh) {
  62154. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  62155. });
  62156. }
  62157. });
  62158. }
  62159. webVrController.attachToPoseControlledCamera(_this);
  62160. // since this is async - sanity check. Is the controller already stored?
  62161. if (_this.controllers.indexOf(webVrController) === -1) {
  62162. //add to the controllers array
  62163. _this.controllers.push(webVrController);
  62164. //did we find enough controllers? Great! let the developer know.
  62165. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  62166. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  62167. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  62168. // So we're overriding setting left & right manually to be sure
  62169. var firstViveWandDetected = false;
  62170. for (var i = 0; i < _this.controllers.length; i++) {
  62171. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  62172. if (!firstViveWandDetected) {
  62173. firstViveWandDetected = true;
  62174. _this.controllers[i].hand = "left";
  62175. }
  62176. else {
  62177. _this.controllers[i].hand = "right";
  62178. }
  62179. }
  62180. }
  62181. _this._onControllersAttached(_this.controllers);
  62182. }
  62183. }
  62184. }
  62185. else {
  62186. _this.nonVRControllers.push(gp);
  62187. if (_this._onNonVRControllerAttached) {
  62188. _this._onNonVRControllerAttached(gp);
  62189. }
  62190. }
  62191. });
  62192. };
  62193. return WebVRFreeCamera;
  62194. }(BABYLON.FreeCamera));
  62195. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  62196. })(BABYLON || (BABYLON = {}));
  62197. //# sourceMappingURL=babylon.webVRCamera.js.map
  62198. /// <reference path="babylon.freeCamera.ts" />
  62199. var BABYLON;
  62200. (function (BABYLON) {
  62201. // We're mainly based on the logic defined into the FreeCamera code
  62202. var DeviceOrientationCamera = (function (_super) {
  62203. __extends(DeviceOrientationCamera, _super);
  62204. function DeviceOrientationCamera(name, position, scene) {
  62205. var _this = _super.call(this, name, position, scene) || this;
  62206. _this._quaternionCache = new BABYLON.Quaternion();
  62207. _this.inputs.addDeviceOrientation();
  62208. return _this;
  62209. }
  62210. DeviceOrientationCamera.prototype.getClassName = function () {
  62211. return "DeviceOrientationCamera";
  62212. };
  62213. DeviceOrientationCamera.prototype._checkInputs = function () {
  62214. _super.prototype._checkInputs.call(this);
  62215. this._quaternionCache.copyFrom(this.rotationQuaternion);
  62216. if (this._initialQuaternion) {
  62217. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  62218. }
  62219. };
  62220. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  62221. var _this = this;
  62222. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  62223. //can only work if this camera has a rotation quaternion already.
  62224. if (!this.rotationQuaternion)
  62225. return;
  62226. if (!this._initialQuaternion) {
  62227. this._initialQuaternion = new BABYLON.Quaternion();
  62228. }
  62229. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  62230. ['x', 'y', 'z'].forEach(function (axisName) {
  62231. if (!axis[axisName]) {
  62232. _this._initialQuaternion[axisName] = 0;
  62233. }
  62234. else {
  62235. _this._initialQuaternion[axisName] *= -1;
  62236. }
  62237. });
  62238. this._initialQuaternion.normalize();
  62239. //force rotation update
  62240. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  62241. };
  62242. return DeviceOrientationCamera;
  62243. }(BABYLON.FreeCamera));
  62244. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  62245. })(BABYLON || (BABYLON = {}));
  62246. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  62247. var BABYLON;
  62248. (function (BABYLON) {
  62249. var VRDeviceOrientationFreeCamera = (function (_super) {
  62250. __extends(VRDeviceOrientationFreeCamera, _super);
  62251. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  62252. if (compensateDistortion === void 0) { compensateDistortion = true; }
  62253. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  62254. var _this = _super.call(this, name, position, scene) || this;
  62255. vrCameraMetrics.compensateDistortion = compensateDistortion;
  62256. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  62257. return _this;
  62258. }
  62259. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  62260. return "VRDeviceOrientationFreeCamera";
  62261. };
  62262. return VRDeviceOrientationFreeCamera;
  62263. }(BABYLON.DeviceOrientationCamera));
  62264. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  62265. var VRDeviceOrientationGamepadCamera = (function (_super) {
  62266. __extends(VRDeviceOrientationGamepadCamera, _super);
  62267. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  62268. if (compensateDistortion === void 0) { compensateDistortion = true; }
  62269. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  62270. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  62271. _this.inputs.addGamepad();
  62272. return _this;
  62273. }
  62274. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  62275. return "VRDeviceOrientationGamepadCamera";
  62276. };
  62277. return VRDeviceOrientationGamepadCamera;
  62278. }(VRDeviceOrientationFreeCamera));
  62279. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  62280. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  62281. __extends(VRDeviceOrientationArcRotateCamera, _super);
  62282. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  62283. if (compensateDistortion === void 0) { compensateDistortion = true; }
  62284. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  62285. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  62286. vrCameraMetrics.compensateDistortion = compensateDistortion;
  62287. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  62288. _this.inputs.addVRDeviceOrientation();
  62289. return _this;
  62290. }
  62291. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  62292. return "VRDeviceOrientationArcRotateCamera";
  62293. };
  62294. return VRDeviceOrientationArcRotateCamera;
  62295. }(BABYLON.ArcRotateCamera));
  62296. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  62297. })(BABYLON || (BABYLON = {}));
  62298. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  62299. /// <reference path="babylon.freeCamera.ts" />
  62300. /// <reference path="babylon.arcRotateCamera.ts" />
  62301. /// <reference path="babylon.gamepadCamera.ts" />
  62302. /// <reference path="babylon.universalCamera.ts" />
  62303. var BABYLON;
  62304. (function (BABYLON) {
  62305. var AnaglyphFreeCamera = (function (_super) {
  62306. __extends(AnaglyphFreeCamera, _super);
  62307. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  62308. var _this = _super.call(this, name, position, scene) || this;
  62309. _this.interaxialDistance = interaxialDistance;
  62310. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  62311. return _this;
  62312. }
  62313. AnaglyphFreeCamera.prototype.getClassName = function () {
  62314. return "AnaglyphFreeCamera";
  62315. };
  62316. return AnaglyphFreeCamera;
  62317. }(BABYLON.FreeCamera));
  62318. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  62319. var AnaglyphArcRotateCamera = (function (_super) {
  62320. __extends(AnaglyphArcRotateCamera, _super);
  62321. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  62322. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  62323. _this.interaxialDistance = interaxialDistance;
  62324. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  62325. return _this;
  62326. }
  62327. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  62328. return "AnaglyphArcRotateCamera";
  62329. };
  62330. return AnaglyphArcRotateCamera;
  62331. }(BABYLON.ArcRotateCamera));
  62332. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  62333. var AnaglyphGamepadCamera = (function (_super) {
  62334. __extends(AnaglyphGamepadCamera, _super);
  62335. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  62336. var _this = _super.call(this, name, position, scene) || this;
  62337. _this.interaxialDistance = interaxialDistance;
  62338. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  62339. return _this;
  62340. }
  62341. AnaglyphGamepadCamera.prototype.getClassName = function () {
  62342. return "AnaglyphGamepadCamera";
  62343. };
  62344. return AnaglyphGamepadCamera;
  62345. }(BABYLON.GamepadCamera));
  62346. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  62347. var AnaglyphUniversalCamera = (function (_super) {
  62348. __extends(AnaglyphUniversalCamera, _super);
  62349. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  62350. var _this = _super.call(this, name, position, scene) || this;
  62351. _this.interaxialDistance = interaxialDistance;
  62352. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  62353. return _this;
  62354. }
  62355. AnaglyphUniversalCamera.prototype.getClassName = function () {
  62356. return "AnaglyphUniversalCamera";
  62357. };
  62358. return AnaglyphUniversalCamera;
  62359. }(BABYLON.UniversalCamera));
  62360. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  62361. var StereoscopicFreeCamera = (function (_super) {
  62362. __extends(StereoscopicFreeCamera, _super);
  62363. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  62364. var _this = _super.call(this, name, position, scene) || this;
  62365. _this.interaxialDistance = interaxialDistance;
  62366. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  62367. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  62368. return _this;
  62369. }
  62370. StereoscopicFreeCamera.prototype.getClassName = function () {
  62371. return "StereoscopicFreeCamera";
  62372. };
  62373. return StereoscopicFreeCamera;
  62374. }(BABYLON.FreeCamera));
  62375. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  62376. var StereoscopicArcRotateCamera = (function (_super) {
  62377. __extends(StereoscopicArcRotateCamera, _super);
  62378. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  62379. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  62380. _this.interaxialDistance = interaxialDistance;
  62381. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  62382. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  62383. return _this;
  62384. }
  62385. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  62386. return "StereoscopicArcRotateCamera";
  62387. };
  62388. return StereoscopicArcRotateCamera;
  62389. }(BABYLON.ArcRotateCamera));
  62390. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  62391. var StereoscopicGamepadCamera = (function (_super) {
  62392. __extends(StereoscopicGamepadCamera, _super);
  62393. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  62394. var _this = _super.call(this, name, position, scene) || this;
  62395. _this.interaxialDistance = interaxialDistance;
  62396. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  62397. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  62398. return _this;
  62399. }
  62400. StereoscopicGamepadCamera.prototype.getClassName = function () {
  62401. return "StereoscopicGamepadCamera";
  62402. };
  62403. return StereoscopicGamepadCamera;
  62404. }(BABYLON.GamepadCamera));
  62405. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  62406. var StereoscopicUniversalCamera = (function (_super) {
  62407. __extends(StereoscopicUniversalCamera, _super);
  62408. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  62409. var _this = _super.call(this, name, position, scene) || this;
  62410. _this.interaxialDistance = interaxialDistance;
  62411. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  62412. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  62413. return _this;
  62414. }
  62415. StereoscopicUniversalCamera.prototype.getClassName = function () {
  62416. return "StereoscopicUniversalCamera";
  62417. };
  62418. return StereoscopicUniversalCamera;
  62419. }(BABYLON.UniversalCamera));
  62420. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  62421. })(BABYLON || (BABYLON = {}));
  62422. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  62423. // Mainly based on these 2 articles :
  62424. // 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
  62425. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  62426. var BABYLON;
  62427. (function (BABYLON) {
  62428. var JoystickAxis;
  62429. (function (JoystickAxis) {
  62430. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  62431. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  62432. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  62433. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  62434. var VirtualJoystick = (function () {
  62435. function VirtualJoystick(leftJoystick) {
  62436. var _this = this;
  62437. if (leftJoystick) {
  62438. this._leftJoystick = true;
  62439. }
  62440. else {
  62441. this._leftJoystick = false;
  62442. }
  62443. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  62444. VirtualJoystick._globalJoystickIndex++;
  62445. // By default left & right arrow keys are moving the X
  62446. // and up & down keys are moving the Y
  62447. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  62448. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  62449. this.reverseLeftRight = false;
  62450. this.reverseUpDown = false;
  62451. // collections of pointers
  62452. this._touches = new BABYLON.StringDictionary();
  62453. this.deltaPosition = BABYLON.Vector3.Zero();
  62454. this._joystickSensibility = 25;
  62455. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  62456. this._rotationSpeed = 25;
  62457. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  62458. this._rotateOnAxisRelativeToMesh = false;
  62459. this._onResize = function (evt) {
  62460. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  62461. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  62462. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  62463. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  62464. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  62465. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  62466. };
  62467. // injecting a canvas element on top of the canvas 3D game
  62468. if (!VirtualJoystick.vjCanvas) {
  62469. window.addEventListener("resize", this._onResize, false);
  62470. VirtualJoystick.vjCanvas = document.createElement("canvas");
  62471. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  62472. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  62473. VirtualJoystick.vjCanvas.width = window.innerWidth;
  62474. VirtualJoystick.vjCanvas.height = window.innerHeight;
  62475. VirtualJoystick.vjCanvas.style.width = "100%";
  62476. VirtualJoystick.vjCanvas.style.height = "100%";
  62477. VirtualJoystick.vjCanvas.style.position = "absolute";
  62478. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  62479. VirtualJoystick.vjCanvas.style.top = "0px";
  62480. VirtualJoystick.vjCanvas.style.left = "0px";
  62481. VirtualJoystick.vjCanvas.style.zIndex = "5";
  62482. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  62483. // Support for jQuery PEP polyfill
  62484. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  62485. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  62486. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  62487. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  62488. document.body.appendChild(VirtualJoystick.vjCanvas);
  62489. }
  62490. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  62491. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  62492. this.pressed = false;
  62493. // default joystick color
  62494. this._joystickColor = "cyan";
  62495. this._joystickPointerID = -1;
  62496. // current joystick position
  62497. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  62498. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  62499. // origin joystick position
  62500. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  62501. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  62502. this._onPointerDownHandlerRef = function (evt) {
  62503. _this._onPointerDown(evt);
  62504. };
  62505. this._onPointerMoveHandlerRef = function (evt) {
  62506. _this._onPointerMove(evt);
  62507. };
  62508. this._onPointerOutHandlerRef = function (evt) {
  62509. _this._onPointerUp(evt);
  62510. };
  62511. this._onPointerUpHandlerRef = function (evt) {
  62512. _this._onPointerUp(evt);
  62513. };
  62514. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  62515. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  62516. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  62517. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  62518. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  62519. evt.preventDefault(); // Disables system menu
  62520. }, false);
  62521. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  62522. }
  62523. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  62524. this._joystickSensibility = newJoystickSensibility;
  62525. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  62526. };
  62527. VirtualJoystick.prototype._onPointerDown = function (e) {
  62528. var positionOnScreenCondition;
  62529. e.preventDefault();
  62530. if (this._leftJoystick === true) {
  62531. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  62532. }
  62533. else {
  62534. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  62535. }
  62536. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  62537. // First contact will be dedicated to the virtual joystick
  62538. this._joystickPointerID = e.pointerId;
  62539. this._joystickPointerStartPos.x = e.clientX;
  62540. this._joystickPointerStartPos.y = e.clientY;
  62541. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  62542. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  62543. this._deltaJoystickVector.x = 0;
  62544. this._deltaJoystickVector.y = 0;
  62545. this.pressed = true;
  62546. this._touches.add(e.pointerId.toString(), e);
  62547. }
  62548. else {
  62549. // You can only trigger the action buttons with a joystick declared
  62550. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  62551. this._action();
  62552. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  62553. }
  62554. }
  62555. };
  62556. VirtualJoystick.prototype._onPointerMove = function (e) {
  62557. // If the current pointer is the one associated to the joystick (first touch contact)
  62558. if (this._joystickPointerID == e.pointerId) {
  62559. this._joystickPointerPos.x = e.clientX;
  62560. this._joystickPointerPos.y = e.clientY;
  62561. this._deltaJoystickVector = this._joystickPointerPos.clone();
  62562. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  62563. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  62564. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  62565. switch (this._axisTargetedByLeftAndRight) {
  62566. case JoystickAxis.X:
  62567. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  62568. break;
  62569. case JoystickAxis.Y:
  62570. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  62571. break;
  62572. case JoystickAxis.Z:
  62573. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  62574. break;
  62575. }
  62576. var directionUpDown = this.reverseUpDown ? 1 : -1;
  62577. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  62578. switch (this._axisTargetedByUpAndDown) {
  62579. case JoystickAxis.X:
  62580. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  62581. break;
  62582. case JoystickAxis.Y:
  62583. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  62584. break;
  62585. case JoystickAxis.Z:
  62586. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  62587. break;
  62588. }
  62589. }
  62590. else {
  62591. var data = this._touches.get(e.pointerId.toString());
  62592. if (data) {
  62593. data.x = e.clientX;
  62594. data.y = e.clientY;
  62595. }
  62596. }
  62597. };
  62598. VirtualJoystick.prototype._onPointerUp = function (e) {
  62599. if (this._joystickPointerID == e.pointerId) {
  62600. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  62601. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  62602. this._joystickPointerID = -1;
  62603. this.pressed = false;
  62604. }
  62605. else {
  62606. var touch = this._touches.get(e.pointerId.toString());
  62607. if (touch) {
  62608. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  62609. }
  62610. }
  62611. this._deltaJoystickVector.x = 0;
  62612. this._deltaJoystickVector.y = 0;
  62613. this._touches.remove(e.pointerId.toString());
  62614. };
  62615. /**
  62616. * Change the color of the virtual joystick
  62617. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  62618. */
  62619. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  62620. this._joystickColor = newColor;
  62621. };
  62622. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  62623. this._action = action;
  62624. };
  62625. // Define which axis you'd like to control for left & right
  62626. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  62627. switch (axis) {
  62628. case JoystickAxis.X:
  62629. case JoystickAxis.Y:
  62630. case JoystickAxis.Z:
  62631. this._axisTargetedByLeftAndRight = axis;
  62632. break;
  62633. default:
  62634. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  62635. break;
  62636. }
  62637. };
  62638. // Define which axis you'd like to control for up & down
  62639. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  62640. switch (axis) {
  62641. case JoystickAxis.X:
  62642. case JoystickAxis.Y:
  62643. case JoystickAxis.Z:
  62644. this._axisTargetedByUpAndDown = axis;
  62645. break;
  62646. default:
  62647. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  62648. break;
  62649. }
  62650. };
  62651. VirtualJoystick.prototype._clearCanvas = function () {
  62652. if (this._leftJoystick) {
  62653. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  62654. }
  62655. else {
  62656. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  62657. }
  62658. };
  62659. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  62660. var _this = this;
  62661. if (this.pressed) {
  62662. this._touches.forEach(function (key, touch) {
  62663. if (touch.pointerId === _this._joystickPointerID) {
  62664. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  62665. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  62666. VirtualJoystick.vjCanvasContext.beginPath();
  62667. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  62668. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  62669. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  62670. VirtualJoystick.vjCanvasContext.stroke();
  62671. VirtualJoystick.vjCanvasContext.closePath();
  62672. VirtualJoystick.vjCanvasContext.beginPath();
  62673. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  62674. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  62675. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  62676. VirtualJoystick.vjCanvasContext.stroke();
  62677. VirtualJoystick.vjCanvasContext.closePath();
  62678. VirtualJoystick.vjCanvasContext.beginPath();
  62679. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  62680. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  62681. VirtualJoystick.vjCanvasContext.stroke();
  62682. VirtualJoystick.vjCanvasContext.closePath();
  62683. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  62684. }
  62685. else {
  62686. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  62687. VirtualJoystick.vjCanvasContext.beginPath();
  62688. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  62689. VirtualJoystick.vjCanvasContext.beginPath();
  62690. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  62691. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  62692. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  62693. VirtualJoystick.vjCanvasContext.stroke();
  62694. VirtualJoystick.vjCanvasContext.closePath();
  62695. touch.prevX = touch.x;
  62696. touch.prevY = touch.y;
  62697. }
  62698. ;
  62699. });
  62700. }
  62701. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  62702. };
  62703. VirtualJoystick.prototype.releaseCanvas = function () {
  62704. if (VirtualJoystick.vjCanvas) {
  62705. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  62706. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  62707. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  62708. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  62709. window.removeEventListener("resize", this._onResize);
  62710. document.body.removeChild(VirtualJoystick.vjCanvas);
  62711. VirtualJoystick.vjCanvas = null;
  62712. }
  62713. };
  62714. return VirtualJoystick;
  62715. }());
  62716. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  62717. VirtualJoystick._globalJoystickIndex = 0;
  62718. BABYLON.VirtualJoystick = VirtualJoystick;
  62719. })(BABYLON || (BABYLON = {}));
  62720. //# sourceMappingURL=babylon.virtualJoystick.js.map
  62721. var BABYLON;
  62722. (function (BABYLON) {
  62723. // We're mainly based on the logic defined into the FreeCamera code
  62724. var VirtualJoysticksCamera = (function (_super) {
  62725. __extends(VirtualJoysticksCamera, _super);
  62726. function VirtualJoysticksCamera(name, position, scene) {
  62727. var _this = _super.call(this, name, position, scene) || this;
  62728. _this.inputs.addVirtualJoystick();
  62729. return _this;
  62730. }
  62731. VirtualJoysticksCamera.prototype.getClassName = function () {
  62732. return "VirtualJoysticksCamera";
  62733. };
  62734. return VirtualJoysticksCamera;
  62735. }(BABYLON.FreeCamera));
  62736. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  62737. })(BABYLON || (BABYLON = {}));
  62738. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  62739. var BABYLON;
  62740. (function (BABYLON) {
  62741. var FreeCameraVirtualJoystickInput = (function () {
  62742. function FreeCameraVirtualJoystickInput() {
  62743. }
  62744. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  62745. return this._leftjoystick;
  62746. };
  62747. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  62748. return this._rightjoystick;
  62749. };
  62750. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  62751. if (this._leftjoystick) {
  62752. var camera = this.camera;
  62753. var speed = camera._computeLocalCameraSpeed() * 50;
  62754. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  62755. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  62756. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  62757. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  62758. if (!this._leftjoystick.pressed) {
  62759. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  62760. }
  62761. if (!this._rightjoystick.pressed) {
  62762. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  62763. }
  62764. }
  62765. };
  62766. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  62767. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  62768. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  62769. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  62770. this._leftjoystick.setJoystickSensibility(0.15);
  62771. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  62772. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  62773. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  62774. this._rightjoystick.reverseUpDown = true;
  62775. this._rightjoystick.setJoystickSensibility(0.05);
  62776. this._rightjoystick.setJoystickColor("yellow");
  62777. };
  62778. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  62779. this._leftjoystick.releaseCanvas();
  62780. this._rightjoystick.releaseCanvas();
  62781. };
  62782. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  62783. return "FreeCameraVirtualJoystickInput";
  62784. };
  62785. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  62786. return "virtualJoystick";
  62787. };
  62788. return FreeCameraVirtualJoystickInput;
  62789. }());
  62790. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  62791. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  62792. })(BABYLON || (BABYLON = {}));
  62793. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  62794. var BABYLON;
  62795. (function (BABYLON) {
  62796. var SimplificationSettings = (function () {
  62797. function SimplificationSettings(quality, distance, optimizeMesh) {
  62798. this.quality = quality;
  62799. this.distance = distance;
  62800. this.optimizeMesh = optimizeMesh;
  62801. }
  62802. return SimplificationSettings;
  62803. }());
  62804. BABYLON.SimplificationSettings = SimplificationSettings;
  62805. var SimplificationQueue = (function () {
  62806. function SimplificationQueue() {
  62807. this.running = false;
  62808. this._simplificationArray = [];
  62809. }
  62810. SimplificationQueue.prototype.addTask = function (task) {
  62811. this._simplificationArray.push(task);
  62812. };
  62813. SimplificationQueue.prototype.executeNext = function () {
  62814. var task = this._simplificationArray.pop();
  62815. if (task) {
  62816. this.running = true;
  62817. this.runSimplification(task);
  62818. }
  62819. else {
  62820. this.running = false;
  62821. }
  62822. };
  62823. SimplificationQueue.prototype.runSimplification = function (task) {
  62824. var _this = this;
  62825. if (task.parallelProcessing) {
  62826. //parallel simplifier
  62827. task.settings.forEach(function (setting) {
  62828. var simplifier = _this.getSimplifier(task);
  62829. simplifier.simplify(setting, function (newMesh) {
  62830. task.mesh.addLODLevel(setting.distance, newMesh);
  62831. newMesh.isVisible = true;
  62832. //check if it is the last
  62833. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  62834. //all done, run the success callback.
  62835. task.successCallback();
  62836. }
  62837. _this.executeNext();
  62838. });
  62839. });
  62840. }
  62841. else {
  62842. //single simplifier.
  62843. var simplifier = this.getSimplifier(task);
  62844. var runDecimation = function (setting, callback) {
  62845. simplifier.simplify(setting, function (newMesh) {
  62846. task.mesh.addLODLevel(setting.distance, newMesh);
  62847. newMesh.isVisible = true;
  62848. //run the next quality level
  62849. callback();
  62850. });
  62851. };
  62852. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  62853. runDecimation(task.settings[loop.index], function () {
  62854. loop.executeNext();
  62855. });
  62856. }, function () {
  62857. //execution ended, run the success callback.
  62858. if (task.successCallback) {
  62859. task.successCallback();
  62860. }
  62861. _this.executeNext();
  62862. });
  62863. }
  62864. };
  62865. SimplificationQueue.prototype.getSimplifier = function (task) {
  62866. switch (task.simplificationType) {
  62867. case SimplificationType.QUADRATIC:
  62868. default:
  62869. return new QuadraticErrorSimplification(task.mesh);
  62870. }
  62871. };
  62872. return SimplificationQueue;
  62873. }());
  62874. BABYLON.SimplificationQueue = SimplificationQueue;
  62875. /**
  62876. * The implemented types of simplification.
  62877. * At the moment only Quadratic Error Decimation is implemented.
  62878. */
  62879. var SimplificationType;
  62880. (function (SimplificationType) {
  62881. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  62882. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  62883. var DecimationTriangle = (function () {
  62884. function DecimationTriangle(vertices) {
  62885. this.vertices = vertices;
  62886. this.error = new Array(4);
  62887. this.deleted = false;
  62888. this.isDirty = false;
  62889. this.deletePending = false;
  62890. this.borderFactor = 0;
  62891. }
  62892. return DecimationTriangle;
  62893. }());
  62894. BABYLON.DecimationTriangle = DecimationTriangle;
  62895. var DecimationVertex = (function () {
  62896. function DecimationVertex(position, id) {
  62897. this.position = position;
  62898. this.id = id;
  62899. this.isBorder = true;
  62900. this.q = new QuadraticMatrix();
  62901. this.triangleCount = 0;
  62902. this.triangleStart = 0;
  62903. this.originalOffsets = [];
  62904. }
  62905. DecimationVertex.prototype.updatePosition = function (newPosition) {
  62906. this.position.copyFrom(newPosition);
  62907. };
  62908. return DecimationVertex;
  62909. }());
  62910. BABYLON.DecimationVertex = DecimationVertex;
  62911. var QuadraticMatrix = (function () {
  62912. function QuadraticMatrix(data) {
  62913. this.data = new Array(10);
  62914. for (var i = 0; i < 10; ++i) {
  62915. if (data && data[i]) {
  62916. this.data[i] = data[i];
  62917. }
  62918. else {
  62919. this.data[i] = 0;
  62920. }
  62921. }
  62922. }
  62923. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  62924. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  62925. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  62926. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  62927. return det;
  62928. };
  62929. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  62930. for (var i = 0; i < 10; ++i) {
  62931. this.data[i] += matrix.data[i];
  62932. }
  62933. };
  62934. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  62935. for (var i = 0; i < 10; ++i) {
  62936. this.data[i] += data[i];
  62937. }
  62938. };
  62939. QuadraticMatrix.prototype.add = function (matrix) {
  62940. var m = new QuadraticMatrix();
  62941. for (var i = 0; i < 10; ++i) {
  62942. m.data[i] = this.data[i] + matrix.data[i];
  62943. }
  62944. return m;
  62945. };
  62946. QuadraticMatrix.FromData = function (a, b, c, d) {
  62947. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  62948. };
  62949. //returning an array to avoid garbage collection
  62950. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  62951. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  62952. };
  62953. return QuadraticMatrix;
  62954. }());
  62955. BABYLON.QuadraticMatrix = QuadraticMatrix;
  62956. var Reference = (function () {
  62957. function Reference(vertexId, triangleId) {
  62958. this.vertexId = vertexId;
  62959. this.triangleId = triangleId;
  62960. }
  62961. return Reference;
  62962. }());
  62963. BABYLON.Reference = Reference;
  62964. /**
  62965. * An implementation of the Quadratic Error simplification algorithm.
  62966. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  62967. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  62968. * @author RaananW
  62969. */
  62970. var QuadraticErrorSimplification = (function () {
  62971. function QuadraticErrorSimplification(_mesh) {
  62972. this._mesh = _mesh;
  62973. this.initialized = false;
  62974. this.syncIterations = 5000;
  62975. this.aggressiveness = 7;
  62976. this.decimationIterations = 100;
  62977. this.boundingBoxEpsilon = BABYLON.Epsilon;
  62978. }
  62979. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  62980. var _this = this;
  62981. this.initDecimatedMesh();
  62982. //iterating through the submeshes array, one after the other.
  62983. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  62984. _this.initWithMesh(loop.index, function () {
  62985. _this.runDecimation(settings, loop.index, function () {
  62986. loop.executeNext();
  62987. });
  62988. }, settings.optimizeMesh);
  62989. }, function () {
  62990. setTimeout(function () {
  62991. successCallback(_this._reconstructedMesh);
  62992. }, 0);
  62993. });
  62994. };
  62995. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  62996. var _this = this;
  62997. var gCount = 0;
  62998. triangle.vertices.forEach(function (vertex) {
  62999. var count = 0;
  63000. var vPos = vertex.position;
  63001. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  63002. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  63003. ++count;
  63004. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  63005. ++count;
  63006. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  63007. ++count;
  63008. if (count > 1) {
  63009. ++gCount;
  63010. }
  63011. ;
  63012. });
  63013. if (gCount > 1) {
  63014. console.log(triangle, gCount);
  63015. }
  63016. return gCount > 1;
  63017. };
  63018. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  63019. var _this = this;
  63020. var targetCount = ~~(this.triangles.length * settings.quality);
  63021. var deletedTriangles = 0;
  63022. var triangleCount = this.triangles.length;
  63023. var iterationFunction = function (iteration, callback) {
  63024. setTimeout(function () {
  63025. if (iteration % 5 === 0) {
  63026. _this.updateMesh(iteration === 0);
  63027. }
  63028. for (var i = 0; i < _this.triangles.length; ++i) {
  63029. _this.triangles[i].isDirty = false;
  63030. }
  63031. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  63032. var trianglesIterator = function (i) {
  63033. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  63034. var t = _this.triangles[tIdx];
  63035. if (!t)
  63036. return;
  63037. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  63038. return;
  63039. }
  63040. for (var j = 0; j < 3; ++j) {
  63041. if (t.error[j] < threshold) {
  63042. var deleted0 = [];
  63043. var deleted1 = [];
  63044. var v0 = t.vertices[j];
  63045. var v1 = t.vertices[(j + 1) % 3];
  63046. if (v0.isBorder || v1.isBorder)
  63047. continue;
  63048. var p = BABYLON.Vector3.Zero();
  63049. var n = BABYLON.Vector3.Zero();
  63050. var uv = BABYLON.Vector2.Zero();
  63051. var color = new BABYLON.Color4(0, 0, 0, 1);
  63052. _this.calculateError(v0, v1, p, n, uv, color);
  63053. var delTr = [];
  63054. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  63055. continue;
  63056. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  63057. continue;
  63058. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  63059. continue;
  63060. var uniqueArray = [];
  63061. delTr.forEach(function (deletedT) {
  63062. if (uniqueArray.indexOf(deletedT) === -1) {
  63063. deletedT.deletePending = true;
  63064. uniqueArray.push(deletedT);
  63065. }
  63066. });
  63067. if (uniqueArray.length % 2 !== 0) {
  63068. continue;
  63069. }
  63070. v0.q = v1.q.add(v0.q);
  63071. v0.updatePosition(p);
  63072. var tStart = _this.references.length;
  63073. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  63074. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  63075. var tCount = _this.references.length - tStart;
  63076. if (tCount <= v0.triangleCount) {
  63077. if (tCount) {
  63078. for (var c = 0; c < tCount; c++) {
  63079. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  63080. }
  63081. }
  63082. }
  63083. else {
  63084. v0.triangleStart = tStart;
  63085. }
  63086. v0.triangleCount = tCount;
  63087. break;
  63088. }
  63089. }
  63090. };
  63091. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  63092. }, 0);
  63093. };
  63094. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  63095. if (triangleCount - deletedTriangles <= targetCount)
  63096. loop.breakLoop();
  63097. else {
  63098. iterationFunction(loop.index, function () {
  63099. loop.executeNext();
  63100. });
  63101. }
  63102. }, function () {
  63103. setTimeout(function () {
  63104. //reconstruct this part of the mesh
  63105. _this.reconstructMesh(submeshIndex);
  63106. successCallback();
  63107. }, 0);
  63108. });
  63109. };
  63110. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  63111. var _this = this;
  63112. this.vertices = [];
  63113. this.triangles = [];
  63114. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63115. var indices = this._mesh.getIndices();
  63116. var submesh = this._mesh.subMeshes[submeshIndex];
  63117. var findInVertices = function (positionToSearch) {
  63118. if (optimizeMesh) {
  63119. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  63120. if (_this.vertices[ii].position.equals(positionToSearch)) {
  63121. return _this.vertices[ii];
  63122. }
  63123. }
  63124. }
  63125. return null;
  63126. };
  63127. var vertexReferences = [];
  63128. var vertexInit = function (i) {
  63129. var offset = i + submesh.verticesStart;
  63130. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  63131. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  63132. vertex.originalOffsets.push(offset);
  63133. if (vertex.id === _this.vertices.length) {
  63134. _this.vertices.push(vertex);
  63135. }
  63136. vertexReferences.push(vertex.id);
  63137. };
  63138. //var totalVertices = mesh.getTotalVertices();
  63139. var totalVertices = submesh.verticesCount;
  63140. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  63141. var indicesInit = function (i) {
  63142. var offset = (submesh.indexStart / 3) + i;
  63143. var pos = (offset * 3);
  63144. var i0 = indices[pos + 0];
  63145. var i1 = indices[pos + 1];
  63146. var i2 = indices[pos + 2];
  63147. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  63148. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  63149. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  63150. var triangle = new DecimationTriangle([v0, v1, v2]);
  63151. triangle.originalOffset = pos;
  63152. _this.triangles.push(triangle);
  63153. };
  63154. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  63155. _this.init(callback);
  63156. });
  63157. });
  63158. };
  63159. QuadraticErrorSimplification.prototype.init = function (callback) {
  63160. var _this = this;
  63161. var triangleInit1 = function (i) {
  63162. var t = _this.triangles[i];
  63163. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  63164. for (var j = 0; j < 3; j++) {
  63165. 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))));
  63166. }
  63167. };
  63168. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  63169. var triangleInit2 = function (i) {
  63170. var t = _this.triangles[i];
  63171. for (var j = 0; j < 3; ++j) {
  63172. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  63173. }
  63174. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  63175. };
  63176. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  63177. _this.initialized = true;
  63178. callback();
  63179. });
  63180. });
  63181. };
  63182. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  63183. var newTriangles = [];
  63184. var i;
  63185. for (i = 0; i < this.vertices.length; ++i) {
  63186. this.vertices[i].triangleCount = 0;
  63187. }
  63188. var t;
  63189. var j;
  63190. for (i = 0; i < this.triangles.length; ++i) {
  63191. if (!this.triangles[i].deleted) {
  63192. t = this.triangles[i];
  63193. for (j = 0; j < 3; ++j) {
  63194. t.vertices[j].triangleCount = 1;
  63195. }
  63196. newTriangles.push(t);
  63197. }
  63198. }
  63199. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  63200. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  63201. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  63202. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  63203. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63204. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63205. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63206. var vertexCount = 0;
  63207. for (i = 0; i < this.vertices.length; ++i) {
  63208. var vertex = this.vertices[i];
  63209. vertex.id = vertexCount;
  63210. if (vertex.triangleCount) {
  63211. vertex.originalOffsets.forEach(function (originalOffset) {
  63212. newPositionData.push(vertex.position.x);
  63213. newPositionData.push(vertex.position.y);
  63214. newPositionData.push(vertex.position.z);
  63215. newNormalData.push(normalData[originalOffset * 3]);
  63216. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  63217. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  63218. if (uvs && uvs.length) {
  63219. newUVsData.push(uvs[(originalOffset * 2)]);
  63220. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  63221. }
  63222. else if (colorsData && colorsData.length) {
  63223. newColorsData.push(colorsData[(originalOffset * 4)]);
  63224. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  63225. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  63226. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  63227. }
  63228. ++vertexCount;
  63229. });
  63230. }
  63231. }
  63232. var startingIndex = this._reconstructedMesh.getTotalIndices();
  63233. var startingVertex = this._reconstructedMesh.getTotalVertices();
  63234. var submeshesArray = this._reconstructedMesh.subMeshes;
  63235. this._reconstructedMesh.subMeshes = [];
  63236. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  63237. var originalIndices = this._mesh.getIndices();
  63238. for (i = 0; i < newTriangles.length; ++i) {
  63239. t = newTriangles[i]; //now get the new referencing point for each vertex
  63240. [0, 1, 2].forEach(function (idx) {
  63241. var id = originalIndices[t.originalOffset + idx];
  63242. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  63243. if (offset < 0)
  63244. offset = 0;
  63245. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  63246. });
  63247. }
  63248. //overwriting the old vertex buffers and indices.
  63249. this._reconstructedMesh.setIndices(newIndicesArray);
  63250. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  63251. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  63252. if (newUVsData.length > 0)
  63253. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  63254. if (newColorsData.length > 0)
  63255. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  63256. //create submesh
  63257. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  63258. if (submeshIndex > 0) {
  63259. this._reconstructedMesh.subMeshes = [];
  63260. submeshesArray.forEach(function (submesh) {
  63261. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  63262. });
  63263. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  63264. }
  63265. };
  63266. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  63267. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  63268. this._reconstructedMesh.material = this._mesh.material;
  63269. this._reconstructedMesh.parent = this._mesh.parent;
  63270. this._reconstructedMesh.isVisible = false;
  63271. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  63272. };
  63273. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  63274. for (var i = 0; i < vertex1.triangleCount; ++i) {
  63275. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  63276. if (t.deleted)
  63277. continue;
  63278. var s = this.references[vertex1.triangleStart + i].vertexId;
  63279. var v1 = t.vertices[(s + 1) % 3];
  63280. var v2 = t.vertices[(s + 2) % 3];
  63281. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  63282. deletedArray[i] = true;
  63283. delTr.push(t);
  63284. continue;
  63285. }
  63286. var d1 = v1.position.subtract(point);
  63287. d1 = d1.normalize();
  63288. var d2 = v2.position.subtract(point);
  63289. d2 = d2.normalize();
  63290. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  63291. return true;
  63292. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  63293. deletedArray[i] = false;
  63294. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  63295. return true;
  63296. }
  63297. return false;
  63298. };
  63299. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  63300. var newDeleted = deletedTriangles;
  63301. for (var i = 0; i < vertex.triangleCount; ++i) {
  63302. var ref = this.references[vertex.triangleStart + i];
  63303. var t = this.triangles[ref.triangleId];
  63304. if (t.deleted)
  63305. continue;
  63306. if (deletedArray[i] && t.deletePending) {
  63307. t.deleted = true;
  63308. newDeleted++;
  63309. continue;
  63310. }
  63311. t.vertices[ref.vertexId] = origVertex;
  63312. t.isDirty = true;
  63313. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  63314. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  63315. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  63316. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  63317. this.references.push(ref);
  63318. }
  63319. return newDeleted;
  63320. };
  63321. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  63322. for (var i = 0; i < this.vertices.length; ++i) {
  63323. var vCount = [];
  63324. var vId = [];
  63325. var v = this.vertices[i];
  63326. var j;
  63327. for (j = 0; j < v.triangleCount; ++j) {
  63328. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  63329. for (var ii = 0; ii < 3; ii++) {
  63330. var ofs = 0;
  63331. var vv = triangle.vertices[ii];
  63332. while (ofs < vCount.length) {
  63333. if (vId[ofs] === vv.id)
  63334. break;
  63335. ++ofs;
  63336. }
  63337. if (ofs === vCount.length) {
  63338. vCount.push(1);
  63339. vId.push(vv.id);
  63340. }
  63341. else {
  63342. vCount[ofs]++;
  63343. }
  63344. }
  63345. }
  63346. for (j = 0; j < vCount.length; ++j) {
  63347. if (vCount[j] === 1) {
  63348. this.vertices[vId[j]].isBorder = true;
  63349. }
  63350. else {
  63351. this.vertices[vId[j]].isBorder = false;
  63352. }
  63353. }
  63354. }
  63355. };
  63356. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  63357. if (identifyBorders === void 0) { identifyBorders = false; }
  63358. var i;
  63359. if (!identifyBorders) {
  63360. var newTrianglesVector = [];
  63361. for (i = 0; i < this.triangles.length; ++i) {
  63362. if (!this.triangles[i].deleted) {
  63363. newTrianglesVector.push(this.triangles[i]);
  63364. }
  63365. }
  63366. this.triangles = newTrianglesVector;
  63367. }
  63368. for (i = 0; i < this.vertices.length; ++i) {
  63369. this.vertices[i].triangleCount = 0;
  63370. this.vertices[i].triangleStart = 0;
  63371. }
  63372. var t;
  63373. var j;
  63374. var v;
  63375. for (i = 0; i < this.triangles.length; ++i) {
  63376. t = this.triangles[i];
  63377. for (j = 0; j < 3; ++j) {
  63378. v = t.vertices[j];
  63379. v.triangleCount++;
  63380. }
  63381. }
  63382. var tStart = 0;
  63383. for (i = 0; i < this.vertices.length; ++i) {
  63384. this.vertices[i].triangleStart = tStart;
  63385. tStart += this.vertices[i].triangleCount;
  63386. this.vertices[i].triangleCount = 0;
  63387. }
  63388. var newReferences = new Array(this.triangles.length * 3);
  63389. for (i = 0; i < this.triangles.length; ++i) {
  63390. t = this.triangles[i];
  63391. for (j = 0; j < 3; ++j) {
  63392. v = t.vertices[j];
  63393. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  63394. v.triangleCount++;
  63395. }
  63396. }
  63397. this.references = newReferences;
  63398. if (identifyBorders) {
  63399. this.identifyBorder();
  63400. }
  63401. };
  63402. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  63403. var x = point.x;
  63404. var y = point.y;
  63405. var z = point.z;
  63406. 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
  63407. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  63408. };
  63409. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  63410. var q = vertex1.q.add(vertex2.q);
  63411. var border = vertex1.isBorder && vertex2.isBorder;
  63412. var error = 0;
  63413. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  63414. if (qDet !== 0 && !border) {
  63415. if (!pointResult) {
  63416. pointResult = BABYLON.Vector3.Zero();
  63417. }
  63418. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  63419. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  63420. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  63421. error = this.vertexError(q, pointResult);
  63422. }
  63423. else {
  63424. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  63425. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  63426. var error1 = this.vertexError(q, vertex1.position);
  63427. var error2 = this.vertexError(q, vertex2.position);
  63428. var error3 = this.vertexError(q, p3);
  63429. error = Math.min(error1, error2, error3);
  63430. if (error === error1) {
  63431. if (pointResult) {
  63432. pointResult.copyFrom(vertex1.position);
  63433. }
  63434. }
  63435. else if (error === error2) {
  63436. if (pointResult) {
  63437. pointResult.copyFrom(vertex2.position);
  63438. }
  63439. }
  63440. else {
  63441. if (pointResult) {
  63442. pointResult.copyFrom(p3);
  63443. }
  63444. }
  63445. }
  63446. return error;
  63447. };
  63448. return QuadraticErrorSimplification;
  63449. }());
  63450. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  63451. })(BABYLON || (BABYLON = {}));
  63452. //# sourceMappingURL=babylon.meshSimplification.js.map
  63453. var BABYLON;
  63454. (function (BABYLON) {
  63455. var Internals;
  63456. (function (Internals) {
  63457. var MeshLODLevel = (function () {
  63458. function MeshLODLevel(distance, mesh) {
  63459. this.distance = distance;
  63460. this.mesh = mesh;
  63461. }
  63462. return MeshLODLevel;
  63463. }());
  63464. Internals.MeshLODLevel = MeshLODLevel;
  63465. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63466. })(BABYLON || (BABYLON = {}));
  63467. //# sourceMappingURL=babylon.meshLODLevel.js.map
  63468. var BABYLON;
  63469. (function (BABYLON) {
  63470. // Standard optimizations
  63471. var SceneOptimization = (function () {
  63472. function SceneOptimization(priority) {
  63473. if (priority === void 0) { priority = 0; }
  63474. this.priority = priority;
  63475. this.apply = function (scene) {
  63476. return true; // Return true if everything that can be done was applied
  63477. };
  63478. }
  63479. return SceneOptimization;
  63480. }());
  63481. BABYLON.SceneOptimization = SceneOptimization;
  63482. var TextureOptimization = (function (_super) {
  63483. __extends(TextureOptimization, _super);
  63484. function TextureOptimization(priority, maximumSize) {
  63485. if (priority === void 0) { priority = 0; }
  63486. if (maximumSize === void 0) { maximumSize = 1024; }
  63487. var _this = _super.call(this, priority) || this;
  63488. _this.priority = priority;
  63489. _this.maximumSize = maximumSize;
  63490. _this.apply = function (scene) {
  63491. var allDone = true;
  63492. for (var index = 0; index < scene.textures.length; index++) {
  63493. var texture = scene.textures[index];
  63494. if (!texture.canRescale) {
  63495. continue;
  63496. }
  63497. var currentSize = texture.getSize();
  63498. var maxDimension = Math.max(currentSize.width, currentSize.height);
  63499. if (maxDimension > _this.maximumSize) {
  63500. texture.scale(0.5);
  63501. allDone = false;
  63502. }
  63503. }
  63504. return allDone;
  63505. };
  63506. return _this;
  63507. }
  63508. return TextureOptimization;
  63509. }(SceneOptimization));
  63510. BABYLON.TextureOptimization = TextureOptimization;
  63511. var HardwareScalingOptimization = (function (_super) {
  63512. __extends(HardwareScalingOptimization, _super);
  63513. function HardwareScalingOptimization(priority, maximumScale) {
  63514. if (priority === void 0) { priority = 0; }
  63515. if (maximumScale === void 0) { maximumScale = 2; }
  63516. var _this = _super.call(this, priority) || this;
  63517. _this.priority = priority;
  63518. _this.maximumScale = maximumScale;
  63519. _this._currentScale = 1;
  63520. _this.apply = function (scene) {
  63521. _this._currentScale++;
  63522. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  63523. return _this._currentScale >= _this.maximumScale;
  63524. };
  63525. return _this;
  63526. }
  63527. return HardwareScalingOptimization;
  63528. }(SceneOptimization));
  63529. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  63530. var ShadowsOptimization = (function (_super) {
  63531. __extends(ShadowsOptimization, _super);
  63532. function ShadowsOptimization() {
  63533. var _this = _super !== null && _super.apply(this, arguments) || this;
  63534. _this.apply = function (scene) {
  63535. scene.shadowsEnabled = false;
  63536. return true;
  63537. };
  63538. return _this;
  63539. }
  63540. return ShadowsOptimization;
  63541. }(SceneOptimization));
  63542. BABYLON.ShadowsOptimization = ShadowsOptimization;
  63543. var PostProcessesOptimization = (function (_super) {
  63544. __extends(PostProcessesOptimization, _super);
  63545. function PostProcessesOptimization() {
  63546. var _this = _super !== null && _super.apply(this, arguments) || this;
  63547. _this.apply = function (scene) {
  63548. scene.postProcessesEnabled = false;
  63549. return true;
  63550. };
  63551. return _this;
  63552. }
  63553. return PostProcessesOptimization;
  63554. }(SceneOptimization));
  63555. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  63556. var LensFlaresOptimization = (function (_super) {
  63557. __extends(LensFlaresOptimization, _super);
  63558. function LensFlaresOptimization() {
  63559. var _this = _super !== null && _super.apply(this, arguments) || this;
  63560. _this.apply = function (scene) {
  63561. scene.lensFlaresEnabled = false;
  63562. return true;
  63563. };
  63564. return _this;
  63565. }
  63566. return LensFlaresOptimization;
  63567. }(SceneOptimization));
  63568. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  63569. var ParticlesOptimization = (function (_super) {
  63570. __extends(ParticlesOptimization, _super);
  63571. function ParticlesOptimization() {
  63572. var _this = _super !== null && _super.apply(this, arguments) || this;
  63573. _this.apply = function (scene) {
  63574. scene.particlesEnabled = false;
  63575. return true;
  63576. };
  63577. return _this;
  63578. }
  63579. return ParticlesOptimization;
  63580. }(SceneOptimization));
  63581. BABYLON.ParticlesOptimization = ParticlesOptimization;
  63582. var RenderTargetsOptimization = (function (_super) {
  63583. __extends(RenderTargetsOptimization, _super);
  63584. function RenderTargetsOptimization() {
  63585. var _this = _super !== null && _super.apply(this, arguments) || this;
  63586. _this.apply = function (scene) {
  63587. scene.renderTargetsEnabled = false;
  63588. return true;
  63589. };
  63590. return _this;
  63591. }
  63592. return RenderTargetsOptimization;
  63593. }(SceneOptimization));
  63594. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  63595. var MergeMeshesOptimization = (function (_super) {
  63596. __extends(MergeMeshesOptimization, _super);
  63597. function MergeMeshesOptimization() {
  63598. var _this = _super !== null && _super.apply(this, arguments) || this;
  63599. _this._canBeMerged = function (abstractMesh) {
  63600. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  63601. return false;
  63602. }
  63603. var mesh = abstractMesh;
  63604. if (!mesh.isVisible || !mesh.isEnabled()) {
  63605. return false;
  63606. }
  63607. if (mesh.instances.length > 0) {
  63608. return false;
  63609. }
  63610. if (mesh.skeleton || mesh.hasLODLevels) {
  63611. return false;
  63612. }
  63613. if (mesh.parent) {
  63614. return false;
  63615. }
  63616. return true;
  63617. };
  63618. _this.apply = function (scene, updateSelectionTree) {
  63619. var globalPool = scene.meshes.slice(0);
  63620. var globalLength = globalPool.length;
  63621. for (var index = 0; index < globalLength; index++) {
  63622. var currentPool = new Array();
  63623. var current = globalPool[index];
  63624. // Checks
  63625. if (!_this._canBeMerged(current)) {
  63626. continue;
  63627. }
  63628. currentPool.push(current);
  63629. // Find compatible meshes
  63630. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  63631. var otherMesh = globalPool[subIndex];
  63632. if (!_this._canBeMerged(otherMesh)) {
  63633. continue;
  63634. }
  63635. if (otherMesh.material !== current.material) {
  63636. continue;
  63637. }
  63638. if (otherMesh.checkCollisions !== current.checkCollisions) {
  63639. continue;
  63640. }
  63641. currentPool.push(otherMesh);
  63642. globalLength--;
  63643. globalPool.splice(subIndex, 1);
  63644. subIndex--;
  63645. }
  63646. if (currentPool.length < 2) {
  63647. continue;
  63648. }
  63649. // Merge meshes
  63650. BABYLON.Mesh.MergeMeshes(currentPool);
  63651. }
  63652. if (updateSelectionTree != undefined) {
  63653. if (updateSelectionTree) {
  63654. scene.createOrUpdateSelectionOctree();
  63655. }
  63656. }
  63657. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  63658. scene.createOrUpdateSelectionOctree();
  63659. }
  63660. return true;
  63661. };
  63662. return _this;
  63663. }
  63664. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  63665. get: function () {
  63666. return MergeMeshesOptimization._UpdateSelectionTree;
  63667. },
  63668. set: function (value) {
  63669. MergeMeshesOptimization._UpdateSelectionTree = value;
  63670. },
  63671. enumerable: true,
  63672. configurable: true
  63673. });
  63674. return MergeMeshesOptimization;
  63675. }(SceneOptimization));
  63676. MergeMeshesOptimization._UpdateSelectionTree = false;
  63677. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  63678. // Options
  63679. var SceneOptimizerOptions = (function () {
  63680. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  63681. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  63682. if (trackerDuration === void 0) { trackerDuration = 2000; }
  63683. this.targetFrameRate = targetFrameRate;
  63684. this.trackerDuration = trackerDuration;
  63685. this.optimizations = new Array();
  63686. }
  63687. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  63688. var result = new SceneOptimizerOptions(targetFrameRate);
  63689. var priority = 0;
  63690. result.optimizations.push(new MergeMeshesOptimization(priority));
  63691. result.optimizations.push(new ShadowsOptimization(priority));
  63692. result.optimizations.push(new LensFlaresOptimization(priority));
  63693. // Next priority
  63694. priority++;
  63695. result.optimizations.push(new PostProcessesOptimization(priority));
  63696. result.optimizations.push(new ParticlesOptimization(priority));
  63697. // Next priority
  63698. priority++;
  63699. result.optimizations.push(new TextureOptimization(priority, 1024));
  63700. return result;
  63701. };
  63702. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  63703. var result = new SceneOptimizerOptions(targetFrameRate);
  63704. var priority = 0;
  63705. result.optimizations.push(new MergeMeshesOptimization(priority));
  63706. result.optimizations.push(new ShadowsOptimization(priority));
  63707. result.optimizations.push(new LensFlaresOptimization(priority));
  63708. // Next priority
  63709. priority++;
  63710. result.optimizations.push(new PostProcessesOptimization(priority));
  63711. result.optimizations.push(new ParticlesOptimization(priority));
  63712. // Next priority
  63713. priority++;
  63714. result.optimizations.push(new TextureOptimization(priority, 512));
  63715. // Next priority
  63716. priority++;
  63717. result.optimizations.push(new RenderTargetsOptimization(priority));
  63718. // Next priority
  63719. priority++;
  63720. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  63721. return result;
  63722. };
  63723. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  63724. var result = new SceneOptimizerOptions(targetFrameRate);
  63725. var priority = 0;
  63726. result.optimizations.push(new MergeMeshesOptimization(priority));
  63727. result.optimizations.push(new ShadowsOptimization(priority));
  63728. result.optimizations.push(new LensFlaresOptimization(priority));
  63729. // Next priority
  63730. priority++;
  63731. result.optimizations.push(new PostProcessesOptimization(priority));
  63732. result.optimizations.push(new ParticlesOptimization(priority));
  63733. // Next priority
  63734. priority++;
  63735. result.optimizations.push(new TextureOptimization(priority, 256));
  63736. // Next priority
  63737. priority++;
  63738. result.optimizations.push(new RenderTargetsOptimization(priority));
  63739. // Next priority
  63740. priority++;
  63741. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  63742. return result;
  63743. };
  63744. return SceneOptimizerOptions;
  63745. }());
  63746. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  63747. // Scene optimizer tool
  63748. var SceneOptimizer = (function () {
  63749. function SceneOptimizer() {
  63750. }
  63751. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  63752. // TODO: add an epsilon
  63753. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  63754. if (onSuccess) {
  63755. onSuccess();
  63756. }
  63757. return;
  63758. }
  63759. // Apply current level of optimizations
  63760. var allDone = true;
  63761. var noOptimizationApplied = true;
  63762. for (var index = 0; index < options.optimizations.length; index++) {
  63763. var optimization = options.optimizations[index];
  63764. if (optimization.priority === currentPriorityLevel) {
  63765. noOptimizationApplied = false;
  63766. allDone = allDone && optimization.apply(scene);
  63767. }
  63768. }
  63769. // If no optimization was applied, this is a failure :(
  63770. if (noOptimizationApplied) {
  63771. if (onFailure) {
  63772. onFailure();
  63773. }
  63774. return;
  63775. }
  63776. // If all optimizations were done, move to next level
  63777. if (allDone) {
  63778. currentPriorityLevel++;
  63779. }
  63780. // Let's the system running for a specific amount of time before checking FPS
  63781. scene.executeWhenReady(function () {
  63782. setTimeout(function () {
  63783. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  63784. }, options.trackerDuration);
  63785. });
  63786. };
  63787. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  63788. if (!options) {
  63789. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  63790. }
  63791. // Let's the system running for a specific amount of time before checking FPS
  63792. scene.executeWhenReady(function () {
  63793. setTimeout(function () {
  63794. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  63795. }, options.trackerDuration);
  63796. });
  63797. };
  63798. return SceneOptimizer;
  63799. }());
  63800. BABYLON.SceneOptimizer = SceneOptimizer;
  63801. })(BABYLON || (BABYLON = {}));
  63802. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  63803. var BABYLON;
  63804. (function (BABYLON) {
  63805. var OutlineRenderer = (function () {
  63806. function OutlineRenderer(scene) {
  63807. this.zOffset = 1;
  63808. this._scene = scene;
  63809. }
  63810. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  63811. var _this = this;
  63812. if (useOverlay === void 0) { useOverlay = false; }
  63813. var scene = this._scene;
  63814. var engine = this._scene.getEngine();
  63815. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  63816. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  63817. return;
  63818. }
  63819. var mesh = subMesh.getRenderingMesh();
  63820. var material = subMesh.getMaterial();
  63821. engine.enableEffect(this._effect);
  63822. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  63823. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  63824. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  63825. // Bones
  63826. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63827. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  63828. }
  63829. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  63830. // Alpha test
  63831. if (material && material.needAlphaTesting()) {
  63832. var alphaTexture = material.getAlphaTestTexture();
  63833. this._effect.setTexture("diffuseSampler", alphaTexture);
  63834. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  63835. }
  63836. engine.setZOffset(-this.zOffset);
  63837. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  63838. engine.setZOffset(0);
  63839. };
  63840. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  63841. var defines = [];
  63842. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  63843. var mesh = subMesh.getMesh();
  63844. var material = subMesh.getMaterial();
  63845. // Alpha test
  63846. if (material && material.needAlphaTesting()) {
  63847. defines.push("#define ALPHATEST");
  63848. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63849. attribs.push(BABYLON.VertexBuffer.UVKind);
  63850. defines.push("#define UV1");
  63851. }
  63852. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  63853. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63854. defines.push("#define UV2");
  63855. }
  63856. }
  63857. // Bones
  63858. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63859. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63860. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63861. if (mesh.numBoneInfluencers > 4) {
  63862. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63863. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63864. }
  63865. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63866. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  63867. }
  63868. else {
  63869. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63870. }
  63871. // Instances
  63872. if (useInstances) {
  63873. defines.push("#define INSTANCES");
  63874. attribs.push("world0");
  63875. attribs.push("world1");
  63876. attribs.push("world2");
  63877. attribs.push("world3");
  63878. }
  63879. // Get correct effect
  63880. var join = defines.join("\n");
  63881. if (this._cachedDefines !== join) {
  63882. this._cachedDefines = join;
  63883. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  63884. }
  63885. return this._effect.isReady();
  63886. };
  63887. return OutlineRenderer;
  63888. }());
  63889. BABYLON.OutlineRenderer = OutlineRenderer;
  63890. })(BABYLON || (BABYLON = {}));
  63891. //# sourceMappingURL=babylon.outlineRenderer.js.map
  63892. var BABYLON;
  63893. (function (BABYLON) {
  63894. var FaceAdjacencies = (function () {
  63895. function FaceAdjacencies() {
  63896. this.edges = new Array();
  63897. this.edgesConnectedCount = 0;
  63898. }
  63899. return FaceAdjacencies;
  63900. }());
  63901. var EdgesRenderer = (function () {
  63902. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  63903. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  63904. if (epsilon === void 0) { epsilon = 0.95; }
  63905. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  63906. this.edgesWidthScalerForOrthographic = 1000.0;
  63907. this.edgesWidthScalerForPerspective = 50.0;
  63908. this._linesPositions = new Array();
  63909. this._linesNormals = new Array();
  63910. this._linesIndices = new Array();
  63911. this._buffers = {};
  63912. this._checkVerticesInsteadOfIndices = false;
  63913. this._source = source;
  63914. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  63915. this._epsilon = epsilon;
  63916. this._prepareRessources();
  63917. this._generateEdgesLines();
  63918. }
  63919. EdgesRenderer.prototype._prepareRessources = function () {
  63920. if (this._lineShader) {
  63921. return;
  63922. }
  63923. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  63924. attributes: ["position", "normal"],
  63925. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  63926. });
  63927. this._lineShader.disableDepthWrite = true;
  63928. this._lineShader.backFaceCulling = false;
  63929. };
  63930. EdgesRenderer.prototype.dispose = function () {
  63931. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  63932. if (buffer) {
  63933. buffer.dispose();
  63934. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  63935. }
  63936. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  63937. if (buffer) {
  63938. buffer.dispose();
  63939. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  63940. }
  63941. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  63942. this._lineShader.dispose();
  63943. };
  63944. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  63945. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  63946. return 0;
  63947. }
  63948. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  63949. return 1;
  63950. }
  63951. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  63952. return 2;
  63953. }
  63954. return -1;
  63955. };
  63956. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  63957. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  63958. return 0;
  63959. }
  63960. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  63961. return 1;
  63962. }
  63963. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  63964. return 2;
  63965. }
  63966. return -1;
  63967. };
  63968. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  63969. var needToCreateLine;
  63970. if (edge === undefined) {
  63971. needToCreateLine = true;
  63972. }
  63973. else {
  63974. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  63975. needToCreateLine = dotProduct < this._epsilon;
  63976. }
  63977. if (needToCreateLine) {
  63978. var offset = this._linesPositions.length / 3;
  63979. var normal = p0.subtract(p1);
  63980. normal.normalize();
  63981. // Positions
  63982. this._linesPositions.push(p0.x);
  63983. this._linesPositions.push(p0.y);
  63984. this._linesPositions.push(p0.z);
  63985. this._linesPositions.push(p0.x);
  63986. this._linesPositions.push(p0.y);
  63987. this._linesPositions.push(p0.z);
  63988. this._linesPositions.push(p1.x);
  63989. this._linesPositions.push(p1.y);
  63990. this._linesPositions.push(p1.z);
  63991. this._linesPositions.push(p1.x);
  63992. this._linesPositions.push(p1.y);
  63993. this._linesPositions.push(p1.z);
  63994. // Normals
  63995. this._linesNormals.push(p1.x);
  63996. this._linesNormals.push(p1.y);
  63997. this._linesNormals.push(p1.z);
  63998. this._linesNormals.push(-1);
  63999. this._linesNormals.push(p1.x);
  64000. this._linesNormals.push(p1.y);
  64001. this._linesNormals.push(p1.z);
  64002. this._linesNormals.push(1);
  64003. this._linesNormals.push(p0.x);
  64004. this._linesNormals.push(p0.y);
  64005. this._linesNormals.push(p0.z);
  64006. this._linesNormals.push(-1);
  64007. this._linesNormals.push(p0.x);
  64008. this._linesNormals.push(p0.y);
  64009. this._linesNormals.push(p0.z);
  64010. this._linesNormals.push(1);
  64011. // Indices
  64012. this._linesIndices.push(offset);
  64013. this._linesIndices.push(offset + 1);
  64014. this._linesIndices.push(offset + 2);
  64015. this._linesIndices.push(offset);
  64016. this._linesIndices.push(offset + 2);
  64017. this._linesIndices.push(offset + 3);
  64018. }
  64019. };
  64020. EdgesRenderer.prototype._generateEdgesLines = function () {
  64021. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64022. var indices = this._source.getIndices();
  64023. // First let's find adjacencies
  64024. var adjacencies = new Array();
  64025. var faceNormals = new Array();
  64026. var index;
  64027. var faceAdjacencies;
  64028. // Prepare faces
  64029. for (index = 0; index < indices.length; index += 3) {
  64030. faceAdjacencies = new FaceAdjacencies();
  64031. var p0Index = indices[index];
  64032. var p1Index = indices[index + 1];
  64033. var p2Index = indices[index + 2];
  64034. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  64035. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  64036. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  64037. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  64038. faceNormal.normalize();
  64039. faceNormals.push(faceNormal);
  64040. adjacencies.push(faceAdjacencies);
  64041. }
  64042. // Scan
  64043. for (index = 0; index < adjacencies.length; index++) {
  64044. faceAdjacencies = adjacencies[index];
  64045. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  64046. var otherFaceAdjacencies = adjacencies[otherIndex];
  64047. if (faceAdjacencies.edgesConnectedCount === 3) {
  64048. break;
  64049. }
  64050. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  64051. continue;
  64052. }
  64053. var otherP0 = indices[otherIndex * 3];
  64054. var otherP1 = indices[otherIndex * 3 + 1];
  64055. var otherP2 = indices[otherIndex * 3 + 2];
  64056. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  64057. var otherEdgeIndex;
  64058. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  64059. continue;
  64060. }
  64061. switch (edgeIndex) {
  64062. case 0:
  64063. if (this._checkVerticesInsteadOfIndices) {
  64064. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  64065. }
  64066. else {
  64067. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  64068. }
  64069. break;
  64070. case 1:
  64071. if (this._checkVerticesInsteadOfIndices) {
  64072. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  64073. }
  64074. else {
  64075. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  64076. }
  64077. break;
  64078. case 2:
  64079. if (this._checkVerticesInsteadOfIndices) {
  64080. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  64081. }
  64082. else {
  64083. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  64084. }
  64085. break;
  64086. }
  64087. if (otherEdgeIndex === -1) {
  64088. continue;
  64089. }
  64090. faceAdjacencies.edges[edgeIndex] = otherIndex;
  64091. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  64092. faceAdjacencies.edgesConnectedCount++;
  64093. otherFaceAdjacencies.edgesConnectedCount++;
  64094. if (faceAdjacencies.edgesConnectedCount === 3) {
  64095. break;
  64096. }
  64097. }
  64098. }
  64099. }
  64100. // Create lines
  64101. for (index = 0; index < adjacencies.length; index++) {
  64102. // 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
  64103. var current = adjacencies[index];
  64104. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  64105. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  64106. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  64107. }
  64108. // Merge into a single mesh
  64109. var engine = this._source.getScene().getEngine();
  64110. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  64111. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  64112. this._ib = engine.createIndexBuffer(this._linesIndices);
  64113. this._indicesCount = this._linesIndices.length;
  64114. };
  64115. EdgesRenderer.prototype.render = function () {
  64116. if (!this._lineShader.isReady()) {
  64117. return;
  64118. }
  64119. var scene = this._source.getScene();
  64120. var engine = scene.getEngine();
  64121. this._lineShader._preBind();
  64122. // VBOs
  64123. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  64124. scene.resetCachedMaterial();
  64125. this._lineShader.setColor4("color", this._source.edgesColor);
  64126. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  64127. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  64128. }
  64129. else {
  64130. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  64131. }
  64132. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  64133. this._lineShader.bind(this._source.getWorldMatrix());
  64134. // Draw order
  64135. engine.draw(true, 0, this._indicesCount);
  64136. this._lineShader.unbind();
  64137. engine.setDepthWrite(true);
  64138. };
  64139. return EdgesRenderer;
  64140. }());
  64141. BABYLON.EdgesRenderer = EdgesRenderer;
  64142. })(BABYLON || (BABYLON = {}));
  64143. //# sourceMappingURL=babylon.edgesRenderer.js.map
  64144. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  64145. /// <reference path="..\Math\babylon.math.ts" />
  64146. var BABYLON;
  64147. (function (BABYLON) {
  64148. /**
  64149. * Special Glow Blur post process only blurring the alpha channel
  64150. * It enforces keeping the most luminous color in the color channel.
  64151. */
  64152. var GlowBlurPostProcess = (function (_super) {
  64153. __extends(GlowBlurPostProcess, _super);
  64154. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  64155. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64156. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  64157. _this.direction = direction;
  64158. _this.kernel = kernel;
  64159. _this.onApplyObservable.add(function (effect) {
  64160. effect.setFloat2("screenSize", _this.width, _this.height);
  64161. effect.setVector2("direction", _this.direction);
  64162. effect.setFloat("blurWidth", _this.kernel);
  64163. });
  64164. return _this;
  64165. }
  64166. return GlowBlurPostProcess;
  64167. }(BABYLON.PostProcess));
  64168. /**
  64169. * The highlight layer Helps adding a glow effect around a mesh.
  64170. *
  64171. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  64172. * glowy meshes to your scene.
  64173. *
  64174. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  64175. */
  64176. var HighlightLayer = (function () {
  64177. /**
  64178. * Instantiates a new highlight Layer and references it to the scene..
  64179. * @param name The name of the layer
  64180. * @param scene The scene to use the layer in
  64181. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  64182. */
  64183. function HighlightLayer(name, scene, options) {
  64184. this.name = name;
  64185. this._vertexBuffers = {};
  64186. this._mainTextureDesiredSize = { width: 0, height: 0 };
  64187. this._meshes = {};
  64188. this._maxSize = 0;
  64189. this._shouldRender = false;
  64190. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  64191. this._excludedMeshes = {};
  64192. /**
  64193. * Specifies whether or not the inner glow is ACTIVE in the layer.
  64194. */
  64195. this.innerGlow = true;
  64196. /**
  64197. * Specifies whether or not the outer glow is ACTIVE in the layer.
  64198. */
  64199. this.outerGlow = true;
  64200. /**
  64201. * Specifies wether the highlight layer is enabled or not.
  64202. */
  64203. this.isEnabled = true;
  64204. /**
  64205. * An event triggered when the highlight layer has been disposed.
  64206. * @type {BABYLON.Observable}
  64207. */
  64208. this.onDisposeObservable = new BABYLON.Observable();
  64209. /**
  64210. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  64211. * @type {BABYLON.Observable}
  64212. */
  64213. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  64214. /**
  64215. * An event triggered when the highlight layer is being blurred.
  64216. * @type {BABYLON.Observable}
  64217. */
  64218. this.onBeforeBlurObservable = new BABYLON.Observable();
  64219. /**
  64220. * An event triggered when the highlight layer has been blurred.
  64221. * @type {BABYLON.Observable}
  64222. */
  64223. this.onAfterBlurObservable = new BABYLON.Observable();
  64224. /**
  64225. * An event triggered when the glowing blurred texture is being merged in the scene.
  64226. * @type {BABYLON.Observable}
  64227. */
  64228. this.onBeforeComposeObservable = new BABYLON.Observable();
  64229. /**
  64230. * An event triggered when the glowing blurred texture has been merged in the scene.
  64231. * @type {BABYLON.Observable}
  64232. */
  64233. this.onAfterComposeObservable = new BABYLON.Observable();
  64234. /**
  64235. * An event triggered when the highlight layer changes its size.
  64236. * @type {BABYLON.Observable}
  64237. */
  64238. this.onSizeChangedObservable = new BABYLON.Observable();
  64239. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64240. var engine = scene.getEngine();
  64241. this._engine = engine;
  64242. this._maxSize = this._engine.getCaps().maxTextureSize;
  64243. this._scene.highlightLayers.push(this);
  64244. // Warn on stencil.
  64245. if (!this._engine.isStencilEnable) {
  64246. 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 }");
  64247. }
  64248. // Adapt options
  64249. this._options = options || {
  64250. mainTextureRatio: 0.25,
  64251. blurTextureSizeRatio: 0.5,
  64252. blurHorizontalSize: 1,
  64253. blurVerticalSize: 1,
  64254. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  64255. };
  64256. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  64257. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  64258. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  64259. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  64260. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  64261. // VBO
  64262. var vertices = [];
  64263. vertices.push(1, 1);
  64264. vertices.push(-1, 1);
  64265. vertices.push(-1, -1);
  64266. vertices.push(1, -1);
  64267. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64268. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  64269. // Indices
  64270. var indices = [];
  64271. indices.push(0);
  64272. indices.push(1);
  64273. indices.push(2);
  64274. indices.push(0);
  64275. indices.push(2);
  64276. indices.push(3);
  64277. this._indexBuffer = engine.createIndexBuffer(indices);
  64278. // Effect
  64279. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  64280. // Render target
  64281. this.setMainTextureSize();
  64282. // Create Textures and post processes
  64283. this.createTextureAndPostProcesses();
  64284. }
  64285. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  64286. /**
  64287. * Gets the horizontal size of the blur.
  64288. */
  64289. get: function () {
  64290. return this._horizontalBlurPostprocess.kernel;
  64291. },
  64292. /**
  64293. * Specifies the horizontal size of the blur.
  64294. */
  64295. set: function (value) {
  64296. this._horizontalBlurPostprocess.kernel = value;
  64297. },
  64298. enumerable: true,
  64299. configurable: true
  64300. });
  64301. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  64302. /**
  64303. * Gets the vertical size of the blur.
  64304. */
  64305. get: function () {
  64306. return this._verticalBlurPostprocess.kernel;
  64307. },
  64308. /**
  64309. * Specifies the vertical size of the blur.
  64310. */
  64311. set: function (value) {
  64312. this._verticalBlurPostprocess.kernel = value;
  64313. },
  64314. enumerable: true,
  64315. configurable: true
  64316. });
  64317. Object.defineProperty(HighlightLayer.prototype, "camera", {
  64318. /**
  64319. * Gets the camera attached to the layer.
  64320. */
  64321. get: function () {
  64322. return this._options.camera;
  64323. },
  64324. enumerable: true,
  64325. configurable: true
  64326. });
  64327. /**
  64328. * Creates the render target textures and post processes used in the highlight layer.
  64329. */
  64330. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  64331. var _this = this;
  64332. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  64333. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  64334. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  64335. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  64336. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  64337. width: this._mainTextureDesiredSize.width,
  64338. height: this._mainTextureDesiredSize.height
  64339. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64340. this._mainTexture.activeCamera = this._options.camera;
  64341. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64342. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64343. this._mainTexture.anisotropicFilteringLevel = 1;
  64344. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64345. this._mainTexture.renderParticles = false;
  64346. this._mainTexture.renderList = null;
  64347. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  64348. width: blurTextureWidth,
  64349. height: blurTextureHeight
  64350. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64351. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64352. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64353. this._blurTexture.anisotropicFilteringLevel = 16;
  64354. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64355. this._blurTexture.renderParticles = false;
  64356. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  64357. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  64358. effect.setTexture("textureSampler", _this._mainTexture);
  64359. });
  64360. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  64361. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  64362. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  64363. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  64364. });
  64365. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  64366. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  64367. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  64368. });
  64369. }
  64370. else {
  64371. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  64372. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  64373. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  64374. });
  64375. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  64376. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  64377. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  64378. });
  64379. }
  64380. this._mainTexture.onAfterUnbindObservable.add(function () {
  64381. _this.onBeforeBlurObservable.notifyObservers(_this);
  64382. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  64383. _this.onAfterBlurObservable.notifyObservers(_this);
  64384. });
  64385. // Custom render function
  64386. var renderSubMesh = function (subMesh) {
  64387. var mesh = subMesh.getRenderingMesh();
  64388. var scene = _this._scene;
  64389. var engine = scene.getEngine();
  64390. // Culling
  64391. engine.setState(subMesh.getMaterial().backFaceCulling);
  64392. // Managing instances
  64393. var batch = mesh._getInstancesRenderList(subMesh._id);
  64394. if (batch.mustReturn) {
  64395. return;
  64396. }
  64397. // Excluded Mesh
  64398. if (_this._excludedMeshes[mesh.uniqueId]) {
  64399. return;
  64400. }
  64401. ;
  64402. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  64403. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  64404. var material = subMesh.getMaterial();
  64405. var emissiveTexture = null;
  64406. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  64407. emissiveTexture = material.emissiveTexture;
  64408. }
  64409. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  64410. engine.enableEffect(_this._glowMapGenerationEffect);
  64411. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  64412. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  64413. if (highlightLayerMesh) {
  64414. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  64415. }
  64416. else {
  64417. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  64418. }
  64419. // Alpha test
  64420. if (material && material.needAlphaTesting()) {
  64421. var alphaTexture = material.getAlphaTestTexture();
  64422. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  64423. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64424. }
  64425. // Glow emissive only
  64426. if (emissiveTexture) {
  64427. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  64428. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  64429. }
  64430. // Bones
  64431. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64432. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64433. }
  64434. // Draw
  64435. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  64436. }
  64437. else {
  64438. // Need to reset refresh rate of the shadowMap
  64439. _this._mainTexture.resetRefreshCounter();
  64440. }
  64441. };
  64442. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  64443. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  64444. var index;
  64445. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64446. renderSubMesh(opaqueSubMeshes.data[index]);
  64447. }
  64448. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64449. renderSubMesh(alphaTestSubMeshes.data[index]);
  64450. }
  64451. for (index = 0; index < transparentSubMeshes.length; index++) {
  64452. renderSubMesh(transparentSubMeshes.data[index]);
  64453. }
  64454. };
  64455. this._mainTexture.onClearObservable.add(function (engine) {
  64456. engine.clear(HighlightLayer.neutralColor, true, true, true);
  64457. });
  64458. };
  64459. /**
  64460. * Checks for the readiness of the element composing the layer.
  64461. * @param subMesh the mesh to check for
  64462. * @param useInstances specify wether or not to use instances to render the mesh
  64463. * @param emissiveTexture the associated emissive texture used to generate the glow
  64464. * @return true if ready otherwise, false
  64465. */
  64466. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  64467. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  64468. return false;
  64469. }
  64470. var defines = [];
  64471. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64472. var mesh = subMesh.getMesh();
  64473. var material = subMesh.getMaterial();
  64474. var uv1 = false;
  64475. var uv2 = false;
  64476. // Alpha test
  64477. if (material && material.needAlphaTesting()) {
  64478. var alphaTexture = material.getAlphaTestTexture();
  64479. if (alphaTexture) {
  64480. defines.push("#define ALPHATEST");
  64481. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  64482. alphaTexture.coordinatesIndex === 1) {
  64483. defines.push("#define DIFFUSEUV2");
  64484. uv2 = true;
  64485. }
  64486. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64487. defines.push("#define DIFFUSEUV1");
  64488. uv1 = true;
  64489. }
  64490. }
  64491. }
  64492. // Emissive
  64493. if (emissiveTexture) {
  64494. defines.push("#define EMISSIVE");
  64495. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  64496. emissiveTexture.coordinatesIndex === 1) {
  64497. defines.push("#define EMISSIVEUV2");
  64498. uv2 = true;
  64499. }
  64500. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64501. defines.push("#define EMISSIVEUV1");
  64502. uv1 = true;
  64503. }
  64504. }
  64505. if (uv1) {
  64506. attribs.push(BABYLON.VertexBuffer.UVKind);
  64507. defines.push("#define UV1");
  64508. }
  64509. if (uv2) {
  64510. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64511. defines.push("#define UV2");
  64512. }
  64513. // Bones
  64514. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64515. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64516. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64517. if (mesh.numBoneInfluencers > 4) {
  64518. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64519. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64520. }
  64521. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64522. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  64523. }
  64524. else {
  64525. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64526. }
  64527. // Instances
  64528. if (useInstances) {
  64529. defines.push("#define INSTANCES");
  64530. attribs.push("world0");
  64531. attribs.push("world1");
  64532. attribs.push("world2");
  64533. attribs.push("world3");
  64534. }
  64535. // Get correct effect
  64536. var join = defines.join("\n");
  64537. if (this._cachedDefines !== join) {
  64538. this._cachedDefines = join;
  64539. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  64540. }
  64541. return this._glowMapGenerationEffect.isReady();
  64542. };
  64543. /**
  64544. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  64545. */
  64546. HighlightLayer.prototype.render = function () {
  64547. var currentEffect = this._glowMapMergeEffect;
  64548. // Check
  64549. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  64550. return;
  64551. var engine = this._scene.getEngine();
  64552. this.onBeforeComposeObservable.notifyObservers(this);
  64553. // Render
  64554. engine.enableEffect(currentEffect);
  64555. engine.setState(false);
  64556. // Cache
  64557. var previousStencilBuffer = engine.getStencilBuffer();
  64558. var previousStencilFunction = engine.getStencilFunction();
  64559. var previousStencilMask = engine.getStencilMask();
  64560. var previousStencilOperationPass = engine.getStencilOperationPass();
  64561. var previousStencilOperationFail = engine.getStencilOperationFail();
  64562. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  64563. var previousAlphaMode = engine.getAlphaMode();
  64564. // Texture
  64565. currentEffect.setTexture("textureSampler", this._blurTexture);
  64566. // VBOs
  64567. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  64568. // Stencil operations
  64569. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  64570. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  64571. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  64572. // Draw order
  64573. engine.setAlphaMode(this._options.alphaBlendingMode);
  64574. engine.setStencilMask(0x00);
  64575. engine.setStencilBuffer(true);
  64576. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  64577. if (this.outerGlow) {
  64578. currentEffect.setFloat("offset", 0);
  64579. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  64580. engine.draw(true, 0, 6);
  64581. }
  64582. if (this.innerGlow) {
  64583. currentEffect.setFloat("offset", 1);
  64584. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  64585. engine.draw(true, 0, 6);
  64586. }
  64587. // Restore Cache
  64588. engine.setStencilFunction(previousStencilFunction);
  64589. engine.setStencilMask(previousStencilMask);
  64590. engine.setAlphaMode(previousAlphaMode);
  64591. engine.setStencilBuffer(previousStencilBuffer);
  64592. engine.setStencilOperationPass(previousStencilOperationPass);
  64593. engine.setStencilOperationFail(previousStencilOperationFail);
  64594. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  64595. engine._stencilState.reset();
  64596. this.onAfterComposeObservable.notifyObservers(this);
  64597. // Handle size changes.
  64598. var size = this._mainTexture.getSize();
  64599. this.setMainTextureSize();
  64600. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  64601. // Recreate RTT and post processes on size change.
  64602. this.onSizeChangedObservable.notifyObservers(this);
  64603. this.disposeTextureAndPostProcesses();
  64604. this.createTextureAndPostProcesses();
  64605. }
  64606. };
  64607. /**
  64608. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  64609. * @param mesh The mesh to exclude from the highlight layer
  64610. */
  64611. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  64612. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  64613. if (!meshExcluded) {
  64614. this._excludedMeshes[mesh.uniqueId] = {
  64615. mesh: mesh,
  64616. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  64617. mesh.getEngine().setStencilBuffer(false);
  64618. }),
  64619. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  64620. mesh.getEngine().setStencilBuffer(true);
  64621. }),
  64622. };
  64623. }
  64624. };
  64625. /**
  64626. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  64627. * @param mesh The mesh to highlight
  64628. */
  64629. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  64630. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  64631. if (meshExcluded) {
  64632. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  64633. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  64634. }
  64635. this._excludedMeshes[mesh.uniqueId] = undefined;
  64636. };
  64637. /**
  64638. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  64639. * @param mesh The mesh to highlight
  64640. * @param color The color of the highlight
  64641. * @param glowEmissiveOnly Extract the glow from the emissive texture
  64642. */
  64643. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  64644. var _this = this;
  64645. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  64646. var meshHighlight = this._meshes[mesh.uniqueId];
  64647. if (meshHighlight) {
  64648. meshHighlight.color = color;
  64649. }
  64650. else {
  64651. this._meshes[mesh.uniqueId] = {
  64652. mesh: mesh,
  64653. color: color,
  64654. // Lambda required for capture due to Observable this context
  64655. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  64656. if (_this._excludedMeshes[mesh.uniqueId]) {
  64657. _this.defaultStencilReference(mesh);
  64658. }
  64659. else {
  64660. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  64661. }
  64662. }),
  64663. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  64664. glowEmissiveOnly: glowEmissiveOnly
  64665. };
  64666. }
  64667. this._shouldRender = true;
  64668. };
  64669. /**
  64670. * Remove a mesh from the highlight layer in order to make it stop glowing.
  64671. * @param mesh The mesh to highlight
  64672. */
  64673. HighlightLayer.prototype.removeMesh = function (mesh) {
  64674. var meshHighlight = this._meshes[mesh.uniqueId];
  64675. if (meshHighlight) {
  64676. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  64677. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  64678. }
  64679. this._meshes[mesh.uniqueId] = undefined;
  64680. this._shouldRender = false;
  64681. for (var meshHighlightToCheck in this._meshes) {
  64682. if (meshHighlightToCheck) {
  64683. this._shouldRender = true;
  64684. break;
  64685. }
  64686. }
  64687. };
  64688. /**
  64689. * Returns true if the layer contains information to display, otherwise false.
  64690. */
  64691. HighlightLayer.prototype.shouldRender = function () {
  64692. return this.isEnabled && this._shouldRender;
  64693. };
  64694. /**
  64695. * Sets the main texture desired size which is the closest power of two
  64696. * of the engine canvas size.
  64697. */
  64698. HighlightLayer.prototype.setMainTextureSize = function () {
  64699. if (this._options.mainTextureFixedSize) {
  64700. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  64701. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  64702. }
  64703. else {
  64704. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  64705. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  64706. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  64707. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  64708. }
  64709. };
  64710. /**
  64711. * Force the stencil to the normal expected value for none glowing parts
  64712. */
  64713. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  64714. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  64715. };
  64716. /**
  64717. * Dispose only the render target textures and post process.
  64718. */
  64719. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  64720. this._blurTexture.dispose();
  64721. this._mainTexture.dispose();
  64722. this._downSamplePostprocess.dispose();
  64723. this._horizontalBlurPostprocess.dispose();
  64724. this._verticalBlurPostprocess.dispose();
  64725. };
  64726. /**
  64727. * Dispose the highlight layer and free resources.
  64728. */
  64729. HighlightLayer.prototype.dispose = function () {
  64730. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64731. if (vertexBuffer) {
  64732. vertexBuffer.dispose();
  64733. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64734. }
  64735. if (this._indexBuffer) {
  64736. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64737. this._indexBuffer = null;
  64738. }
  64739. // Clean textures and post processes
  64740. this.disposeTextureAndPostProcesses();
  64741. // Clean mesh references
  64742. for (var id in this._meshes) {
  64743. var meshHighlight = this._meshes[id];
  64744. if (meshHighlight && meshHighlight.mesh) {
  64745. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  64746. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  64747. }
  64748. }
  64749. this._meshes = null;
  64750. for (var id in this._excludedMeshes) {
  64751. var meshHighlight = this._excludedMeshes[id];
  64752. if (meshHighlight) {
  64753. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  64754. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  64755. }
  64756. }
  64757. this._excludedMeshes = null;
  64758. // Remove from scene
  64759. var index = this._scene.highlightLayers.indexOf(this, 0);
  64760. if (index > -1) {
  64761. this._scene.highlightLayers.splice(index, 1);
  64762. }
  64763. // Callback
  64764. this.onDisposeObservable.notifyObservers(this);
  64765. this.onDisposeObservable.clear();
  64766. this.onBeforeRenderMainTextureObservable.clear();
  64767. this.onBeforeBlurObservable.clear();
  64768. this.onBeforeComposeObservable.clear();
  64769. this.onAfterComposeObservable.clear();
  64770. this.onSizeChangedObservable.clear();
  64771. };
  64772. return HighlightLayer;
  64773. }());
  64774. /**
  64775. * The neutral color used during the preparation of the glow effect.
  64776. * This is black by default as the blend operation is a blend operation.
  64777. */
  64778. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  64779. /**
  64780. * Stencil value used for glowing meshes.
  64781. */
  64782. HighlightLayer.glowingMeshStencilReference = 0x02;
  64783. /**
  64784. * Stencil value used for the other meshes in the scene.
  64785. */
  64786. HighlightLayer.normalMeshStencilReference = 0x01;
  64787. BABYLON.HighlightLayer = HighlightLayer;
  64788. })(BABYLON || (BABYLON = {}));
  64789. //# sourceMappingURL=babylon.highlightlayer.js.map
  64790. var BABYLON;
  64791. (function (BABYLON) {
  64792. var MeshAssetTask = (function () {
  64793. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  64794. this.name = name;
  64795. this.meshesNames = meshesNames;
  64796. this.rootUrl = rootUrl;
  64797. this.sceneFilename = sceneFilename;
  64798. this.isCompleted = false;
  64799. }
  64800. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64801. var _this = this;
  64802. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  64803. _this.loadedMeshes = meshes;
  64804. _this.loadedParticleSystems = particleSystems;
  64805. _this.loadedSkeletons = skeletons;
  64806. _this.isCompleted = true;
  64807. if (_this.onSuccess) {
  64808. _this.onSuccess(_this);
  64809. }
  64810. onSuccess();
  64811. }, null, function () {
  64812. if (_this.onError) {
  64813. _this.onError(_this);
  64814. }
  64815. onError();
  64816. });
  64817. };
  64818. return MeshAssetTask;
  64819. }());
  64820. BABYLON.MeshAssetTask = MeshAssetTask;
  64821. var TextFileAssetTask = (function () {
  64822. function TextFileAssetTask(name, url) {
  64823. this.name = name;
  64824. this.url = url;
  64825. this.isCompleted = false;
  64826. }
  64827. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64828. var _this = this;
  64829. BABYLON.Tools.LoadFile(this.url, function (data) {
  64830. _this.text = data;
  64831. _this.isCompleted = true;
  64832. if (_this.onSuccess) {
  64833. _this.onSuccess(_this);
  64834. }
  64835. onSuccess();
  64836. }, null, scene.database, false, function () {
  64837. if (_this.onError) {
  64838. _this.onError(_this);
  64839. }
  64840. onError();
  64841. });
  64842. };
  64843. return TextFileAssetTask;
  64844. }());
  64845. BABYLON.TextFileAssetTask = TextFileAssetTask;
  64846. var BinaryFileAssetTask = (function () {
  64847. function BinaryFileAssetTask(name, url) {
  64848. this.name = name;
  64849. this.url = url;
  64850. this.isCompleted = false;
  64851. }
  64852. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64853. var _this = this;
  64854. BABYLON.Tools.LoadFile(this.url, function (data) {
  64855. _this.data = data;
  64856. _this.isCompleted = true;
  64857. if (_this.onSuccess) {
  64858. _this.onSuccess(_this);
  64859. }
  64860. onSuccess();
  64861. }, null, scene.database, true, function () {
  64862. if (_this.onError) {
  64863. _this.onError(_this);
  64864. }
  64865. onError();
  64866. });
  64867. };
  64868. return BinaryFileAssetTask;
  64869. }());
  64870. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  64871. var ImageAssetTask = (function () {
  64872. function ImageAssetTask(name, url) {
  64873. this.name = name;
  64874. this.url = url;
  64875. this.isCompleted = false;
  64876. }
  64877. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64878. var _this = this;
  64879. var img = new Image();
  64880. BABYLON.Tools.SetCorsBehavior(this.url, img);
  64881. img.onload = function () {
  64882. _this.image = img;
  64883. _this.isCompleted = true;
  64884. if (_this.onSuccess) {
  64885. _this.onSuccess(_this);
  64886. }
  64887. onSuccess();
  64888. };
  64889. img.onerror = function () {
  64890. if (_this.onError) {
  64891. _this.onError(_this);
  64892. }
  64893. onError();
  64894. };
  64895. img.src = this.url;
  64896. };
  64897. return ImageAssetTask;
  64898. }());
  64899. BABYLON.ImageAssetTask = ImageAssetTask;
  64900. var TextureAssetTask = (function () {
  64901. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  64902. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64903. this.name = name;
  64904. this.url = url;
  64905. this.noMipmap = noMipmap;
  64906. this.invertY = invertY;
  64907. this.samplingMode = samplingMode;
  64908. this.isCompleted = false;
  64909. }
  64910. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64911. var _this = this;
  64912. var onload = function () {
  64913. _this.isCompleted = true;
  64914. if (_this.onSuccess) {
  64915. _this.onSuccess(_this);
  64916. }
  64917. onSuccess();
  64918. };
  64919. var onerror = function () {
  64920. if (_this.onError) {
  64921. _this.onError(_this);
  64922. }
  64923. onError();
  64924. };
  64925. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  64926. };
  64927. return TextureAssetTask;
  64928. }());
  64929. BABYLON.TextureAssetTask = TextureAssetTask;
  64930. var CubeTextureAssetTask = (function () {
  64931. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  64932. this.name = name;
  64933. this.url = url;
  64934. this.extensions = extensions;
  64935. this.noMipmap = noMipmap;
  64936. this.files = files;
  64937. this.isCompleted = false;
  64938. }
  64939. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64940. var _this = this;
  64941. var onload = function () {
  64942. _this.isCompleted = true;
  64943. if (_this.onSuccess) {
  64944. _this.onSuccess(_this);
  64945. }
  64946. onSuccess();
  64947. };
  64948. var onerror = function () {
  64949. if (_this.onError) {
  64950. _this.onError(_this);
  64951. }
  64952. onError();
  64953. };
  64954. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  64955. };
  64956. return CubeTextureAssetTask;
  64957. }());
  64958. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  64959. var HDRCubeTextureAssetTask = (function () {
  64960. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  64961. if (noMipmap === void 0) { noMipmap = false; }
  64962. if (generateHarmonics === void 0) { generateHarmonics = true; }
  64963. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  64964. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  64965. this.name = name;
  64966. this.url = url;
  64967. this.size = size;
  64968. this.noMipmap = noMipmap;
  64969. this.generateHarmonics = generateHarmonics;
  64970. this.useInGammaSpace = useInGammaSpace;
  64971. this.usePMREMGenerator = usePMREMGenerator;
  64972. this.isCompleted = false;
  64973. }
  64974. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64975. var _this = this;
  64976. var onload = function () {
  64977. _this.isCompleted = true;
  64978. if (_this.onSuccess) {
  64979. _this.onSuccess(_this);
  64980. }
  64981. onSuccess();
  64982. };
  64983. var onerror = function () {
  64984. if (_this.onError) {
  64985. _this.onError(_this);
  64986. }
  64987. onError();
  64988. };
  64989. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  64990. };
  64991. return HDRCubeTextureAssetTask;
  64992. }());
  64993. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  64994. var AssetsManager = (function () {
  64995. function AssetsManager(scene) {
  64996. this.tasks = new Array();
  64997. this.waitingTasksCount = 0;
  64998. this.useDefaultLoadingScreen = true;
  64999. this._scene = scene;
  65000. }
  65001. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  65002. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  65003. this.tasks.push(task);
  65004. return task;
  65005. };
  65006. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  65007. var task = new TextFileAssetTask(taskName, url);
  65008. this.tasks.push(task);
  65009. return task;
  65010. };
  65011. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  65012. var task = new BinaryFileAssetTask(taskName, url);
  65013. this.tasks.push(task);
  65014. return task;
  65015. };
  65016. AssetsManager.prototype.addImageTask = function (taskName, url) {
  65017. var task = new ImageAssetTask(taskName, url);
  65018. this.tasks.push(task);
  65019. return task;
  65020. };
  65021. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  65022. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65023. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  65024. this.tasks.push(task);
  65025. return task;
  65026. };
  65027. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  65028. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  65029. this.tasks.push(task);
  65030. return task;
  65031. };
  65032. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  65033. if (noMipmap === void 0) { noMipmap = false; }
  65034. if (generateHarmonics === void 0) { generateHarmonics = true; }
  65035. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  65036. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  65037. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  65038. this.tasks.push(task);
  65039. return task;
  65040. };
  65041. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  65042. this.waitingTasksCount--;
  65043. if (this.waitingTasksCount === 0) {
  65044. if (this.onFinish) {
  65045. this.onFinish(this.tasks);
  65046. }
  65047. this._scene.getEngine().hideLoadingUI();
  65048. }
  65049. };
  65050. AssetsManager.prototype._runTask = function (task) {
  65051. var _this = this;
  65052. task.run(this._scene, function () {
  65053. if (_this.onTaskSuccess) {
  65054. _this.onTaskSuccess(task);
  65055. }
  65056. _this._decreaseWaitingTasksCount();
  65057. }, function () {
  65058. if (_this.onTaskError) {
  65059. _this.onTaskError(task);
  65060. }
  65061. _this._decreaseWaitingTasksCount();
  65062. });
  65063. };
  65064. AssetsManager.prototype.reset = function () {
  65065. this.tasks = new Array();
  65066. return this;
  65067. };
  65068. AssetsManager.prototype.load = function () {
  65069. this.waitingTasksCount = this.tasks.length;
  65070. if (this.waitingTasksCount === 0) {
  65071. if (this.onFinish) {
  65072. this.onFinish(this.tasks);
  65073. }
  65074. return this;
  65075. }
  65076. if (this.useDefaultLoadingScreen) {
  65077. this._scene.getEngine().displayLoadingUI();
  65078. }
  65079. for (var index = 0; index < this.tasks.length; index++) {
  65080. var task = this.tasks[index];
  65081. this._runTask(task);
  65082. }
  65083. return this;
  65084. };
  65085. return AssetsManager;
  65086. }());
  65087. BABYLON.AssetsManager = AssetsManager;
  65088. })(BABYLON || (BABYLON = {}));
  65089. //# sourceMappingURL=babylon.assetsManager.js.map
  65090. var BABYLON;
  65091. (function (BABYLON) {
  65092. var MapTexture = (function (_super) {
  65093. __extends(MapTexture, _super);
  65094. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  65095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65096. if (useMipMap === void 0) { useMipMap = false; }
  65097. if (margin === void 0) { margin = 0; }
  65098. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  65099. _this.name = name;
  65100. _this._size = size;
  65101. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65102. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65103. // Create the rectPackMap that will allocate portion of the texture
  65104. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  65105. // Create the texture that will store the content
  65106. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  65107. return _this;
  65108. }
  65109. /**
  65110. * Allocate a rectangle of a given size in the texture map
  65111. * @param size the size of the rectangle to allocation
  65112. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  65113. */
  65114. MapTexture.prototype.allocateRect = function (size) {
  65115. return this._rectPackingMap.addRect(size);
  65116. };
  65117. /**
  65118. * Free a given rectangle from the texture map
  65119. * @param rectInfo the instance corresponding to the rect to free.
  65120. */
  65121. MapTexture.prototype.freeRect = function (rectInfo) {
  65122. if (rectInfo) {
  65123. rectInfo.freeContent();
  65124. }
  65125. };
  65126. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  65127. /**
  65128. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  65129. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  65130. * @returns {}
  65131. */
  65132. get: function () {
  65133. return this._rectPackingMap.freeSpace;
  65134. },
  65135. enumerable: true,
  65136. configurable: true
  65137. });
  65138. /**
  65139. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  65140. * 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.
  65141. * Don't forget to call unbindTexture when you're done rendering
  65142. * @param rect the zone to render to
  65143. * @param clear true to clear the portion's color/depth data
  65144. */
  65145. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  65146. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  65147. };
  65148. /**
  65149. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  65150. * 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.
  65151. * Don't forget to call unbindTexture when you're done rendering
  65152. * @param pos the position into the texture
  65153. * @param size the portion to fit the clip space to
  65154. * @param clear true to clear the portion's color/depth data
  65155. */
  65156. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  65157. var engine = this.getScene().getEngine();
  65158. engine.bindFramebuffer(this._texture);
  65159. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  65160. if (clear) {
  65161. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  65162. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  65163. }
  65164. };
  65165. /**
  65166. * Unbind the texture map from the rendering engine.
  65167. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  65168. * @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.
  65169. */
  65170. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  65171. // Dump ?
  65172. if (dumpForDebug) {
  65173. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  65174. }
  65175. var engine = this.getScene().getEngine();
  65176. if (this._replacedViewport) {
  65177. engine.setViewport(this._replacedViewport);
  65178. this._replacedViewport = null;
  65179. }
  65180. engine.unBindFramebuffer(this._texture);
  65181. };
  65182. Object.defineProperty(MapTexture.prototype, "canRescale", {
  65183. get: function () {
  65184. return false;
  65185. },
  65186. enumerable: true,
  65187. configurable: true
  65188. });
  65189. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  65190. // Anyway, there's not much point to use this method for this kind of texture I guess
  65191. MapTexture.prototype.clone = function () {
  65192. return null;
  65193. };
  65194. return MapTexture;
  65195. }(BABYLON.Texture));
  65196. BABYLON.MapTexture = MapTexture;
  65197. })(BABYLON || (BABYLON = {}));
  65198. //# sourceMappingURL=babylon.mapTexture.js.map
  65199. var BABYLON;
  65200. (function (BABYLON) {
  65201. /**
  65202. * This class describe a rectangle that were added to the map.
  65203. * You have access to its coordinates either in pixel or normalized (UV)
  65204. */
  65205. var PackedRect = (function () {
  65206. function PackedRect(root, parent, pos, size) {
  65207. this._pos = pos;
  65208. this._size = size;
  65209. this._root = root;
  65210. this._parent = parent;
  65211. this._contentSize = null;
  65212. this._bottomNode = null;
  65213. this._leftNode = null;
  65214. this._initialSize = null;
  65215. this._rightNode = null;
  65216. }
  65217. Object.defineProperty(PackedRect.prototype, "pos", {
  65218. /**
  65219. * @returns the position of this node into the map
  65220. */
  65221. get: function () {
  65222. return this._pos;
  65223. },
  65224. enumerable: true,
  65225. configurable: true
  65226. });
  65227. Object.defineProperty(PackedRect.prototype, "contentSize", {
  65228. /**
  65229. * @returns the size of the rectangle this node handles
  65230. */
  65231. get: function () {
  65232. return this._contentSize;
  65233. },
  65234. enumerable: true,
  65235. configurable: true
  65236. });
  65237. /**
  65238. * Retrieve the inner position (considering the margin) and stores it into the res object
  65239. * @param res must be a valid Vector2 that will contain the inner position after this call
  65240. */
  65241. PackedRect.prototype.getInnerPosToRef = function (res) {
  65242. var m = this._root._margin;
  65243. res.x = this._pos.x + m;
  65244. res.y = this._pos.y + m;
  65245. };
  65246. /**
  65247. * Retrieve the inner size (considering the margin) and stores it into the res object
  65248. * @param res must be a valid Size that will contain the inner size after this call
  65249. */
  65250. PackedRect.prototype.getInnerSizeToRef = function (res) {
  65251. var m = this._root._margin;
  65252. res.width = this._contentSize.width - (m * 2);
  65253. res.height = this._contentSize.height - (m * 2);
  65254. };
  65255. Object.defineProperty(PackedRect.prototype, "UVs", {
  65256. /**
  65257. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  65258. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  65259. */
  65260. get: function () {
  65261. if (!this._contentSize) {
  65262. throw new Error("Can't compute UVs for this object because it's nor allocated");
  65263. }
  65264. return this.getUVsForCustomSize(this._contentSize);
  65265. },
  65266. enumerable: true,
  65267. configurable: true
  65268. });
  65269. /**
  65270. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  65271. * and then using only a part of the PackRect.
  65272. * This method will return the UVs for this part by given the custom size of what you really use
  65273. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  65274. */
  65275. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  65276. var mainWidth = this._root._size.width;
  65277. var mainHeight = this._root._size.height;
  65278. var margin = this._root._margin;
  65279. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  65280. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  65281. var uvs = new Array();
  65282. uvs.push(topLeft);
  65283. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  65284. uvs.push(rightBottom);
  65285. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  65286. return uvs;
  65287. };
  65288. /**
  65289. * Free this rectangle from the map.
  65290. * Call this method when you no longer need the rectangle to be in the map.
  65291. */
  65292. PackedRect.prototype.freeContent = function () {
  65293. if (!this.contentSize) {
  65294. return;
  65295. }
  65296. this._contentSize = null;
  65297. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  65298. this.attemptDefrag();
  65299. };
  65300. Object.defineProperty(PackedRect.prototype, "isUsed", {
  65301. get: function () {
  65302. return this._contentSize != null || this._leftNode != null;
  65303. },
  65304. enumerable: true,
  65305. configurable: true
  65306. });
  65307. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  65308. var node = this.findNode(contentSize);
  65309. // Not enough space...
  65310. if (!node) {
  65311. return null;
  65312. }
  65313. node.splitNode(contentSize);
  65314. return node;
  65315. };
  65316. PackedRect.prototype.findNode = function (size) {
  65317. var resNode = null;
  65318. var margin = this._root._margin * 2;
  65319. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  65320. if (this.isUsed) {
  65321. if (this._leftNode) {
  65322. resNode = this._leftNode.findNode(size);
  65323. }
  65324. if (!resNode && this._rightNode) {
  65325. resNode = this._rightNode.findNode(size);
  65326. }
  65327. if (!resNode && this._bottomNode) {
  65328. resNode = this._bottomNode.findNode(size);
  65329. }
  65330. }
  65331. else if (this._initialSize) {
  65332. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  65333. resNode = this;
  65334. }
  65335. else {
  65336. return null;
  65337. }
  65338. }
  65339. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  65340. resNode = this;
  65341. }
  65342. return resNode;
  65343. };
  65344. PackedRect.prototype.splitNode = function (contentSize) {
  65345. var cs = PackedRect.TpsSize;
  65346. var margin = this._root._margin * 2;
  65347. cs.copyFrom(contentSize);
  65348. cs.width += margin;
  65349. cs.height += margin;
  65350. // 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)
  65351. if (!this._contentSize && this._initialSize) {
  65352. this._contentSize = cs.clone();
  65353. 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));
  65354. return this._leftNode.splitNode(contentSize);
  65355. }
  65356. else {
  65357. this._contentSize = cs.clone();
  65358. this._initialSize = cs.clone();
  65359. if (cs.width !== this._size.width) {
  65360. 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));
  65361. }
  65362. if (cs.height !== this._size.height) {
  65363. 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));
  65364. }
  65365. return this;
  65366. }
  65367. };
  65368. PackedRect.prototype.attemptDefrag = function () {
  65369. if (!this.isUsed && this.isRecursiveFree) {
  65370. this.clearNode();
  65371. if (this._parent) {
  65372. this._parent.attemptDefrag();
  65373. }
  65374. }
  65375. };
  65376. PackedRect.prototype.clearNode = function () {
  65377. this._initialSize = null;
  65378. this._rightNode = null;
  65379. this._bottomNode = null;
  65380. };
  65381. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  65382. get: function () {
  65383. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  65384. },
  65385. enumerable: true,
  65386. configurable: true
  65387. });
  65388. PackedRect.prototype.evalFreeSize = function (size) {
  65389. var levelSize = 0;
  65390. if (!this.isUsed) {
  65391. var margin = this._root._margin;
  65392. var is = this._initialSize;
  65393. if (is) {
  65394. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  65395. }
  65396. else {
  65397. var size_1 = this._size;
  65398. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  65399. }
  65400. }
  65401. if (this._rightNode) {
  65402. levelSize += this._rightNode.evalFreeSize(0);
  65403. }
  65404. if (this._bottomNode) {
  65405. levelSize += this._bottomNode.evalFreeSize(0);
  65406. }
  65407. return levelSize + size;
  65408. };
  65409. return PackedRect;
  65410. }());
  65411. PackedRect.TpsSize = BABYLON.Size.Zero();
  65412. BABYLON.PackedRect = PackedRect;
  65413. /**
  65414. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  65415. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  65416. * 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.
  65417. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  65418. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  65419. */
  65420. var RectPackingMap = (function (_super) {
  65421. __extends(RectPackingMap, _super);
  65422. /**
  65423. * Create an instance of the object with a dimension using the given size
  65424. * @param size The dimension of the rectangle that will contain all the sub ones.
  65425. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  65426. */
  65427. function RectPackingMap(size, margin) {
  65428. if (margin === void 0) { margin = 0; }
  65429. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  65430. _this._margin = margin;
  65431. _this._root = _this;
  65432. return _this;
  65433. }
  65434. /**
  65435. * Add a rectangle, finding the best location to store it into the map
  65436. * @param size the dimension of the rectangle to store
  65437. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  65438. */
  65439. RectPackingMap.prototype.addRect = function (size) {
  65440. var node = this.findAndSplitNode(size);
  65441. return node;
  65442. };
  65443. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  65444. /**
  65445. * Return the current space free normalized between [0;1]
  65446. * @returns {}
  65447. */
  65448. get: function () {
  65449. var freeSize = 0;
  65450. freeSize = this.evalFreeSize(freeSize);
  65451. return freeSize / (this._size.width * this._size.height);
  65452. },
  65453. enumerable: true,
  65454. configurable: true
  65455. });
  65456. return RectPackingMap;
  65457. }(PackedRect));
  65458. BABYLON.RectPackingMap = RectPackingMap;
  65459. })(BABYLON || (BABYLON = {}));
  65460. //# sourceMappingURL=babylon.rectPackingMap.js.map
  65461. var BABYLON;
  65462. (function (BABYLON) {
  65463. var serializedGeometries = [];
  65464. var serializeGeometry = function (geometry, serializationGeometries) {
  65465. if (serializedGeometries[geometry.id]) {
  65466. return;
  65467. }
  65468. if (geometry.doNotSerialize) {
  65469. return;
  65470. }
  65471. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  65472. serializationGeometries.boxes.push(geometry.serialize());
  65473. }
  65474. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  65475. serializationGeometries.spheres.push(geometry.serialize());
  65476. }
  65477. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  65478. serializationGeometries.cylinders.push(geometry.serialize());
  65479. }
  65480. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  65481. serializationGeometries.toruses.push(geometry.serialize());
  65482. }
  65483. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  65484. serializationGeometries.grounds.push(geometry.serialize());
  65485. }
  65486. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  65487. serializationGeometries.planes.push(geometry.serialize());
  65488. }
  65489. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  65490. serializationGeometries.torusKnots.push(geometry.serialize());
  65491. }
  65492. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  65493. throw new Error("Unknown primitive type");
  65494. }
  65495. else {
  65496. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  65497. }
  65498. serializedGeometries[geometry.id] = true;
  65499. };
  65500. var serializeMesh = function (mesh, serializationScene) {
  65501. var serializationObject = {};
  65502. // Geometry
  65503. var geometry = mesh._geometry;
  65504. if (geometry) {
  65505. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  65506. // 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
  65507. serializeGeometry(geometry, serializationScene.geometries);
  65508. }
  65509. }
  65510. // Custom
  65511. if (mesh.serialize) {
  65512. mesh.serialize(serializationObject);
  65513. }
  65514. return serializationObject;
  65515. };
  65516. var finalizeSingleMesh = function (mesh, serializationObject) {
  65517. //only works if the mesh is already loaded
  65518. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  65519. //serialize material
  65520. if (mesh.material) {
  65521. if (mesh.material instanceof BABYLON.StandardMaterial) {
  65522. serializationObject.materials = serializationObject.materials || [];
  65523. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  65524. serializationObject.materials.push(mesh.material.serialize());
  65525. }
  65526. }
  65527. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  65528. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  65529. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  65530. serializationObject.multiMaterials.push(mesh.material.serialize());
  65531. }
  65532. }
  65533. }
  65534. //serialize geometry
  65535. var geometry = mesh._geometry;
  65536. if (geometry) {
  65537. if (!serializationObject.geometries) {
  65538. serializationObject.geometries = {};
  65539. serializationObject.geometries.boxes = [];
  65540. serializationObject.geometries.spheres = [];
  65541. serializationObject.geometries.cylinders = [];
  65542. serializationObject.geometries.toruses = [];
  65543. serializationObject.geometries.grounds = [];
  65544. serializationObject.geometries.planes = [];
  65545. serializationObject.geometries.torusKnots = [];
  65546. serializationObject.geometries.vertexData = [];
  65547. }
  65548. serializeGeometry(geometry, serializationObject.geometries);
  65549. }
  65550. // Skeletons
  65551. if (mesh.skeleton) {
  65552. serializationObject.skeletons = serializationObject.skeletons || [];
  65553. serializationObject.skeletons.push(mesh.skeleton.serialize());
  65554. }
  65555. //serialize the actual mesh
  65556. serializationObject.meshes = serializationObject.meshes || [];
  65557. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  65558. }
  65559. };
  65560. var SceneSerializer = (function () {
  65561. function SceneSerializer() {
  65562. }
  65563. SceneSerializer.ClearCache = function () {
  65564. serializedGeometries = [];
  65565. };
  65566. SceneSerializer.Serialize = function (scene) {
  65567. var serializationObject = {};
  65568. SceneSerializer.ClearCache();
  65569. // Scene
  65570. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  65571. serializationObject.autoClear = scene.autoClear;
  65572. serializationObject.clearColor = scene.clearColor.asArray();
  65573. serializationObject.ambientColor = scene.ambientColor.asArray();
  65574. serializationObject.gravity = scene.gravity.asArray();
  65575. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  65576. serializationObject.workerCollisions = scene.workerCollisions;
  65577. // Fog
  65578. if (scene.fogMode && scene.fogMode !== 0) {
  65579. serializationObject.fogMode = scene.fogMode;
  65580. serializationObject.fogColor = scene.fogColor.asArray();
  65581. serializationObject.fogStart = scene.fogStart;
  65582. serializationObject.fogEnd = scene.fogEnd;
  65583. serializationObject.fogDensity = scene.fogDensity;
  65584. }
  65585. //Physics
  65586. if (scene.isPhysicsEnabled()) {
  65587. serializationObject.physicsEnabled = true;
  65588. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  65589. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  65590. }
  65591. // Metadata
  65592. if (scene.metadata) {
  65593. serializationObject.metadata = scene.metadata;
  65594. }
  65595. // Morph targets
  65596. serializationObject.morphTargetManagers = [];
  65597. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  65598. var abstractMesh = _a[_i];
  65599. var manager = abstractMesh.morphTargetManager;
  65600. if (manager) {
  65601. serializationObject.morphTargetManagers.push(manager.serialize());
  65602. }
  65603. }
  65604. // Lights
  65605. serializationObject.lights = [];
  65606. var index;
  65607. var light;
  65608. for (index = 0; index < scene.lights.length; index++) {
  65609. light = scene.lights[index];
  65610. if (!light.doNotSerialize) {
  65611. serializationObject.lights.push(light.serialize());
  65612. }
  65613. }
  65614. // Cameras
  65615. serializationObject.cameras = [];
  65616. for (index = 0; index < scene.cameras.length; index++) {
  65617. var camera = scene.cameras[index];
  65618. if (!camera.doNotSerialize) {
  65619. serializationObject.cameras.push(camera.serialize());
  65620. }
  65621. }
  65622. if (scene.activeCamera) {
  65623. serializationObject.activeCameraID = scene.activeCamera.id;
  65624. }
  65625. // Animations
  65626. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  65627. // Materials
  65628. serializationObject.materials = [];
  65629. serializationObject.multiMaterials = [];
  65630. var material;
  65631. for (index = 0; index < scene.materials.length; index++) {
  65632. material = scene.materials[index];
  65633. if (!material.doNotSerialize) {
  65634. serializationObject.materials.push(material.serialize());
  65635. }
  65636. }
  65637. // MultiMaterials
  65638. serializationObject.multiMaterials = [];
  65639. for (index = 0; index < scene.multiMaterials.length; index++) {
  65640. var multiMaterial = scene.multiMaterials[index];
  65641. serializationObject.multiMaterials.push(multiMaterial.serialize());
  65642. }
  65643. // Skeletons
  65644. serializationObject.skeletons = [];
  65645. for (index = 0; index < scene.skeletons.length; index++) {
  65646. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  65647. }
  65648. // Geometries
  65649. serializationObject.geometries = {};
  65650. serializationObject.geometries.boxes = [];
  65651. serializationObject.geometries.spheres = [];
  65652. serializationObject.geometries.cylinders = [];
  65653. serializationObject.geometries.toruses = [];
  65654. serializationObject.geometries.grounds = [];
  65655. serializationObject.geometries.planes = [];
  65656. serializationObject.geometries.torusKnots = [];
  65657. serializationObject.geometries.vertexData = [];
  65658. serializedGeometries = [];
  65659. var geometries = scene.getGeometries();
  65660. for (index = 0; index < geometries.length; index++) {
  65661. var geometry = geometries[index];
  65662. if (geometry.isReady()) {
  65663. serializeGeometry(geometry, serializationObject.geometries);
  65664. }
  65665. }
  65666. // Meshes
  65667. serializationObject.meshes = [];
  65668. for (index = 0; index < scene.meshes.length; index++) {
  65669. var abstractMesh = scene.meshes[index];
  65670. if (abstractMesh instanceof BABYLON.Mesh) {
  65671. var mesh = abstractMesh;
  65672. if (!mesh.doNotSerialize) {
  65673. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  65674. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  65675. }
  65676. }
  65677. }
  65678. }
  65679. // Particles Systems
  65680. serializationObject.particleSystems = [];
  65681. for (index = 0; index < scene.particleSystems.length; index++) {
  65682. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  65683. }
  65684. // Lens flares
  65685. serializationObject.lensFlareSystems = [];
  65686. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  65687. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  65688. }
  65689. // Shadows
  65690. serializationObject.shadowGenerators = [];
  65691. for (index = 0; index < scene.lights.length; index++) {
  65692. light = scene.lights[index];
  65693. var shadowGenerator = light.getShadowGenerator();
  65694. if (shadowGenerator) {
  65695. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  65696. }
  65697. }
  65698. // Action Manager
  65699. if (scene.actionManager) {
  65700. serializationObject.actions = scene.actionManager.serialize("scene");
  65701. }
  65702. // Audio
  65703. serializationObject.sounds = [];
  65704. for (index = 0; index < scene.soundTracks.length; index++) {
  65705. var soundtrack = scene.soundTracks[index];
  65706. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  65707. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  65708. }
  65709. }
  65710. return serializationObject;
  65711. };
  65712. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  65713. if (withParents === void 0) { withParents = false; }
  65714. if (withChildren === void 0) { withChildren = false; }
  65715. var serializationObject = {};
  65716. SceneSerializer.ClearCache();
  65717. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  65718. if (withParents || withChildren) {
  65719. //deliberate for loop! not for each, appended should be processed as well.
  65720. for (var i = 0; i < toSerialize.length; ++i) {
  65721. if (withChildren) {
  65722. toSerialize[i].getDescendants().forEach(function (node) {
  65723. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  65724. toSerialize.push(node);
  65725. }
  65726. });
  65727. }
  65728. //make sure the array doesn't contain the object already
  65729. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  65730. toSerialize.push(toSerialize[i].parent);
  65731. }
  65732. }
  65733. }
  65734. toSerialize.forEach(function (mesh) {
  65735. finalizeSingleMesh(mesh, serializationObject);
  65736. });
  65737. return serializationObject;
  65738. };
  65739. return SceneSerializer;
  65740. }());
  65741. BABYLON.SceneSerializer = SceneSerializer;
  65742. })(BABYLON || (BABYLON = {}));
  65743. //# sourceMappingURL=babylon.sceneSerializer.js.map
  65744. var BABYLON;
  65745. (function (BABYLON) {
  65746. var ReflectionProbe = (function () {
  65747. function ReflectionProbe(name, size, scene, generateMipMaps) {
  65748. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65749. var _this = this;
  65750. this.name = name;
  65751. this._viewMatrix = BABYLON.Matrix.Identity();
  65752. this._target = BABYLON.Vector3.Zero();
  65753. this._add = BABYLON.Vector3.Zero();
  65754. this.invertYAxis = false;
  65755. this.position = BABYLON.Vector3.Zero();
  65756. this._scene = scene;
  65757. this._scene.reflectionProbes.push(this);
  65758. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  65759. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  65760. switch (faceIndex) {
  65761. case 0:
  65762. _this._add.copyFromFloats(1, 0, 0);
  65763. break;
  65764. case 1:
  65765. _this._add.copyFromFloats(-1, 0, 0);
  65766. break;
  65767. case 2:
  65768. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  65769. break;
  65770. case 3:
  65771. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  65772. break;
  65773. case 4:
  65774. _this._add.copyFromFloats(0, 0, 1);
  65775. break;
  65776. case 5:
  65777. _this._add.copyFromFloats(0, 0, -1);
  65778. break;
  65779. }
  65780. if (_this._attachedMesh) {
  65781. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  65782. }
  65783. _this.position.addToRef(_this._add, _this._target);
  65784. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  65785. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  65786. });
  65787. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  65788. scene.updateTransformMatrix(true);
  65789. });
  65790. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  65791. }
  65792. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  65793. get: function () {
  65794. return this._renderTargetTexture.samples;
  65795. },
  65796. set: function (value) {
  65797. this._renderTargetTexture.samples = value;
  65798. },
  65799. enumerable: true,
  65800. configurable: true
  65801. });
  65802. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  65803. get: function () {
  65804. return this._renderTargetTexture.refreshRate;
  65805. },
  65806. set: function (value) {
  65807. this._renderTargetTexture.refreshRate = value;
  65808. },
  65809. enumerable: true,
  65810. configurable: true
  65811. });
  65812. ReflectionProbe.prototype.getScene = function () {
  65813. return this._scene;
  65814. };
  65815. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  65816. get: function () {
  65817. return this._renderTargetTexture;
  65818. },
  65819. enumerable: true,
  65820. configurable: true
  65821. });
  65822. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  65823. get: function () {
  65824. return this._renderTargetTexture.renderList;
  65825. },
  65826. enumerable: true,
  65827. configurable: true
  65828. });
  65829. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  65830. this._attachedMesh = mesh;
  65831. };
  65832. ReflectionProbe.prototype.dispose = function () {
  65833. var index = this._scene.reflectionProbes.indexOf(this);
  65834. if (index !== -1) {
  65835. // Remove from the scene if found
  65836. this._scene.reflectionProbes.splice(index, 1);
  65837. }
  65838. if (this._renderTargetTexture) {
  65839. this._renderTargetTexture.dispose();
  65840. this._renderTargetTexture = null;
  65841. }
  65842. };
  65843. return ReflectionProbe;
  65844. }());
  65845. BABYLON.ReflectionProbe = ReflectionProbe;
  65846. })(BABYLON || (BABYLON = {}));
  65847. //# sourceMappingURL=babylon.reflectionProbe.js.map
  65848. var BABYLON;
  65849. (function (BABYLON) {
  65850. var Layer = (function () {
  65851. function Layer(name, imgUrl, scene, isBackground, color) {
  65852. this.name = name;
  65853. this.scale = new BABYLON.Vector2(1, 1);
  65854. this.offset = new BABYLON.Vector2(0, 0);
  65855. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  65856. this.layerMask = 0x0FFFFFFF;
  65857. this._vertexBuffers = {};
  65858. // Events
  65859. /**
  65860. * An event triggered when the layer is disposed.
  65861. * @type {BABYLON.Observable}
  65862. */
  65863. this.onDisposeObservable = new BABYLON.Observable();
  65864. /**
  65865. * An event triggered before rendering the scene
  65866. * @type {BABYLON.Observable}
  65867. */
  65868. this.onBeforeRenderObservable = new BABYLON.Observable();
  65869. /**
  65870. * An event triggered after rendering the scene
  65871. * @type {BABYLON.Observable}
  65872. */
  65873. this.onAfterRenderObservable = new BABYLON.Observable();
  65874. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  65875. this.isBackground = isBackground === undefined ? true : isBackground;
  65876. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  65877. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65878. this._scene.layers.push(this);
  65879. var engine = this._scene.getEngine();
  65880. // VBO
  65881. var vertices = [];
  65882. vertices.push(1, 1);
  65883. vertices.push(-1, 1);
  65884. vertices.push(-1, -1);
  65885. vertices.push(1, -1);
  65886. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65887. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  65888. // Indices
  65889. var indices = [];
  65890. indices.push(0);
  65891. indices.push(1);
  65892. indices.push(2);
  65893. indices.push(0);
  65894. indices.push(2);
  65895. indices.push(3);
  65896. this._indexBuffer = engine.createIndexBuffer(indices);
  65897. // Effects
  65898. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  65899. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  65900. }
  65901. Object.defineProperty(Layer.prototype, "onDispose", {
  65902. set: function (callback) {
  65903. if (this._onDisposeObserver) {
  65904. this.onDisposeObservable.remove(this._onDisposeObserver);
  65905. }
  65906. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  65907. },
  65908. enumerable: true,
  65909. configurable: true
  65910. });
  65911. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  65912. set: function (callback) {
  65913. if (this._onBeforeRenderObserver) {
  65914. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65915. }
  65916. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65917. },
  65918. enumerable: true,
  65919. configurable: true
  65920. });
  65921. Object.defineProperty(Layer.prototype, "onAfterRender", {
  65922. set: function (callback) {
  65923. if (this._onAfterRenderObserver) {
  65924. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65925. }
  65926. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65927. },
  65928. enumerable: true,
  65929. configurable: true
  65930. });
  65931. Layer.prototype.render = function () {
  65932. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  65933. // Check
  65934. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  65935. return;
  65936. var engine = this._scene.getEngine();
  65937. this.onBeforeRenderObservable.notifyObservers(this);
  65938. // Render
  65939. engine.enableEffect(currentEffect);
  65940. engine.setState(false);
  65941. // Texture
  65942. currentEffect.setTexture("textureSampler", this.texture);
  65943. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  65944. // Color
  65945. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  65946. // Scale / offset
  65947. currentEffect.setVector2("offset", this.offset);
  65948. currentEffect.setVector2("scale", this.scale);
  65949. // VBOs
  65950. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  65951. // Draw order
  65952. if (!this.alphaTest) {
  65953. engine.setAlphaMode(this.alphaBlendingMode);
  65954. engine.draw(true, 0, 6);
  65955. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65956. }
  65957. else {
  65958. engine.draw(true, 0, 6);
  65959. }
  65960. this.onAfterRenderObservable.notifyObservers(this);
  65961. };
  65962. Layer.prototype.dispose = function () {
  65963. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65964. if (vertexBuffer) {
  65965. vertexBuffer.dispose();
  65966. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65967. }
  65968. if (this._indexBuffer) {
  65969. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65970. this._indexBuffer = null;
  65971. }
  65972. if (this.texture) {
  65973. this.texture.dispose();
  65974. this.texture = null;
  65975. }
  65976. // Remove from scene
  65977. var index = this._scene.layers.indexOf(this);
  65978. this._scene.layers.splice(index, 1);
  65979. // Callback
  65980. this.onDisposeObservable.notifyObservers(this);
  65981. this.onDisposeObservable.clear();
  65982. this.onAfterRenderObservable.clear();
  65983. this.onBeforeRenderObservable.clear();
  65984. };
  65985. return Layer;
  65986. }());
  65987. BABYLON.Layer = Layer;
  65988. })(BABYLON || (BABYLON = {}));
  65989. //# sourceMappingURL=babylon.layer.js.map
  65990. 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 DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\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<shadowsVertexDeclaration>[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 DIFFUSE\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#ifdef AMBIENT\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#ifdef OPACITY\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#ifdef EMISSIVE\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#ifdef LIGHTMAP\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)\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#ifdef BUMP\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#ifdef BUMP\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\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\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)\nvarying vec2 vSpecularUV;\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#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\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=vec3(1.0,1.0,1.0);\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#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\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 VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#ifdef BUMP\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<shadowsVertexDeclaration>[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 ALBEDO\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#ifdef AMBIENT\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#ifdef OPACITY\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#ifdef EMISSIVE\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#ifdef LIGHTMAP\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) || defined(METALLICWORKFLOW) \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#ifdef MICROSURFACEMAP\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#ifdef BUMP\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 NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\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#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) \nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#ifdef ALPHAFROMALBEDO\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#if defined(ALPHATEST) && defined(ALPHATESTVALUE)\nif (alpha<ALPHATESTVALUE)\ndiscard;\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 METALLICMAP\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\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\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\nlightingInfo info;\nfloat shadow=1.; \n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 lightDiffuseContribution=diffuseBase;\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=specularBase*vLightingIntensity.w;\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 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\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#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\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\nsurfaceRefractionColor*=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=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=lightDiffuseContribution;\n#ifndef EMISSIVEASILLUMINATION\nfinalDiffuse+=surfaceEmissiveColor;\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\nfloat luminanceOverAlpha=0.0;\n#ifdef RADIANCEOVERALPHA\nluminanceOverAlpha+=getLuminance(environmentRadiance);\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nluminanceOverAlpha+=getLuminance(finalSpecular);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nfinalSpecular*=vLightingIntensity.x;\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*alpha,0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular+environmentRadiance+refractance,alpha);\n#ifdef EMISSIVEASILLUMINATION\nfinalColor.rgb+=(surfaceEmissiveColor*vLightingIntensity.y);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n#ifdef LDROUTPUT\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\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}","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;\nvarying vec4 vPosition;\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>\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 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 vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nuniform vec2 biasAndScale;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5; \n#endif\ndepth+=biasAndScale.x;\n#ifdef ESM\ndepth=exp(-min(87.,biasAndScale.y*depth));\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;\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\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\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}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,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(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\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(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;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*finalWorld*vec4(position,1.0);\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 ALPHATEST\nin vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nlayout(location=0) out vec4 color0;\nlayout(location=1) out vec4 color1;\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,0.0);\ncolor1=vec4(normalize(vNormalV),1.0);\n\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;\nconst float GammaEncodePowerApprox=1.0/2.2;\nconst float LinearEncodePowerApprox=2.2;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nuniform float contrast;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\nuniform float cameraExposureLinear;\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color)\n{\nfloat sliceSize=2.0*colorTransformSettings.y; \nfloat sliceContinuous=(color.y-colorTransformSettings.y)*colorTransformSettings.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\nvec2 sliceUV=color.xz;\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=result.bgr;\nreturn color;\n}\nvec4 applyImageProcessing(vec4 result,vec2 viewportXY){\n#ifndef FROMLINEARSPACE\n\nresult.rgb=pow(result.rgb,vec3(LinearEncodePowerApprox));\n#endif\nresult.rgb*=cameraExposureLinear;\n#ifdef VIGNETTE\n\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 \nfloat tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=pow(result.rgb,vec3(GammaEncodePowerApprox));\nresult.rgb=clamp(result.rgb,0.0,1.0);\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=dot(result.rgb,RGBLuminanceCoefficients);\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}\nvoid main(void) \n{\nvec4 result=texture2D(textureSampler,vUV);\nvec2 viewportXY=vUV*2.0-1.0;\nresult=applyImageProcessing(result,viewportXY);\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]\nvoid main(void)\n{\nvec4 blend=vec4(0.);\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\ngl_FragColor=blend;\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}"};
  65991. 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","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if !defined(SHADOWCUBE{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n","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(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\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":"mat3 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}","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};\nuniform sampler2D shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{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\nvec3 shadowsInfo;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{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\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\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)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\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)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\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-darkness,0.,1.); \nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\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))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<depth.z) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<depth.z) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 depth=0.5*clipSpace+vec3(0.5);\nvec2 uv=depth.xy;\nfloat shadowPixelDepth=depth.z;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\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-darkness,0.,1.); \n\n\n\n\n\nreturn esm;\n}\n#endif","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}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\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,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,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,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 SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\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);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x);\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#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \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","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\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#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\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;\n#ifdef REFRACTIONMAP_3D\n#else\nuniform mat4 refractionMatrix;\n#endif\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#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 vec2 vMicrosurfaceTextureLods;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform vec4 opacityParts;\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\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 kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\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/(kPi*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 specularColor,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); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \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 diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\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{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\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.0001));\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 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=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*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 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=max(0.00000000001,dot(vNormal,directionToLightCenterW));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*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 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=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\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":"blend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n","kernelBlurFragment2":"blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  65992. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  65993. module.exports = BABYLON;
  65994. };